LINQ copytodatatable query

I have a linq query that calculates specific data. Now I want the query to be executed with a type DataTable

. Here is the request:

var query = dt.AsEnumerable()
    .GroupBy(row => new
    {
        Name = row.Field<string>("Name")
    })
    .Select(g => new
    {
        Name = g.Key.wcName,
        quantity = g.Count()
    });

      

I heard about .CopyToDataTable

which is used here, but it doesn't show up. How do I convert a query to datatable?

+3


source to share


2 answers


First create a table with schema then select with result IEnumerable<DataRow>

to useCopyToDataTable()



var temp = new DataTable();
temp.Columns.Add("Name", typeof(string));
temp.Columns.Add("Quantity", typeof(int));

var query = dt.AsEnumerable()
    .GroupBy(row => row.Field<string>("Name"))
    .Select(g =>
    {
        var row = temp.NewRow();
        row.SetField("Name", g.Key);
        row.SetField("Quantity", g.Count());
        return row;
    }).CopyToDataTable();

      

+2


source


public static class DataTableToListHelper
    {      
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch (Exception ex)
        {                
            return null;
        }
    }
}
DataTable dt = new DataTable();
connection.Open();
adapter.Fill(dt);
connection.Close();
var entityObjectList = dt.DataTableToList<YOURENTITY>();

      



-1


source







All Articles