Converting anonymous type to DataTable

11,166

Found here:

var result = from p in dataSource 
             group p by p.City into cities 
             select new { Property1 = cities.Key, Property 2= cities.Average(p => p.Age) }; 

dt.Columns.Add("Property1"); 
dt.Columns.Add("Property2"); 
foreach (var item in result) 
{   
    dt.Rows.Add(item.Property1,item.Property2);                 
}

See here for a generic solution: Convert generic List/Enumerable to DataTable?

Share:
11,166
Alexandre
Author by

Alexandre

Updated on June 04, 2022

Comments

  • Alexandre
    Alexandre about 2 years

    What is the fastest way to convert anonymous type to DataTable?

    Update: I want to get and populate DataTable from anonymous type. If reflection is neccesary, how can I to do it using reflection?

  • George Duckett
    George Duckett almost 13 years
    @Alex, If you wanted a generic solution you should have said (also, i edited my answer to provide one).
  • Admin
    Admin over 7 years
    detail summery below