Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting anonymous type to DataTable

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?

like image 577
Alexandre Avatar asked Feb 23 '23 02:02

Alexandre


1 Answers

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?

like image 179
George Duckett Avatar answered Feb 27 '23 09:02

George Duckett