Converting anonymous type to DataTable
What is the fastest way to convert anonymous type to DataTable?
开发者_Go百科Update: I want to get and populate DataTable from anonymous type. If reflection is neccesary, how can I to do it using reflection?
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?
///fill dt1
Dim dt1 As New DataTable dt1 = connection.LoadPoliceData("")
///fll dt2
Dim dt2 As New DataTable dt2 = connection.LoadDataCompare("")
////fill enumerable data(anonymous data) in dt , using linq query
Dim dt As New DataTable
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Mobile", GetType(String))
Dim data1 = (From datarow1 In dt1.AsEnumerable Join datarow2 In dt2.AsEnumerable
On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber")
Select dt.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
Dim i = dt.Rows.Count
record in dt(datatable variable )
///summary fill datatable one (dt1)
Dim dt1 As New DataTable
dt1 = connection.LoadPoliceData("")
///summary fill datatable one (dt2)
Dim dt2 As New DataTable
dt2 = connection.LoadDataCompare("")
/// summary declare datatable save . where i want fill Enumerable data
Dim save As New DataTable
save.Columns.Add("Name", GetType(String))
save.Columns.Add("Mobile", GetType(String))
///summary writing linq query with join of dt1 and dt2 , And datatable(save)
Dim data1 = (From datarow1 In dt1.AsEnumerable Join datarow2 In dt2.AsEnumerable On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber") Select save.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
///summary count of datatable save
Dim i = save.Rows.Count
精彩评论