3

I have a linq query which is calculating particular data. Now I want that query to be typecasted to DataTable. Here is the query :

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

I have heard about .CopyToDataTable which is used here but it is not showing. How can I convert the query to datatable ?

3
  • why do you use dt.AsEnumerable().GroupBy() not just dt.GroupBy() ? Commented May 6, 2015 at 5:06
  • 1
    Refer stackoverflow.com/questions/4460654/… Commented May 6, 2015 at 5:07
  • No, it is giving error 'System.Data.DataTable' does not contain a definition for 'GroupBy' and no extension method 'GroupBy' accepting a first argument of type 'System.Data.DataTable' could be found Commented May 6, 2015 at 5:09

2 Answers 2

3

First create a table with the schema, then Select with the result of IEnumerable<DataRow> in order to use CopyToDataTable()

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(); 
Sign up to request clarification or add additional context in comments.

3 Comments

The new DataTable created is empty. No data is getting inserted in temp
Add temp.Rows.Add(row); after row.SetField("Quantity", g.Count()); will work
@bogojane Opps, I should also edit the name of query. The variable query is the result DataTable already, not the temp
0
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>(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.