将匿名类型转换为DataTable

时间:2011-09-02 09:02:50

标签: c# .net-4.0 datatable asp.net-4.0 anonymous-types

将匿名类型转换为DataTable的最快方法是什么?

更新 我想从匿名类型中获取并填充DataTable。如果反射是必要的,我怎么能用反射来做呢?

3 个答案:

答案 0 :(得分:10)

找到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);                 
}

请点击此处查看通用解决方案:Convert generic List/Enumerable to DataTable?

答案 1 :(得分:0)

///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

记录在dt(数据表变量)

答案 2 :(得分:-1)

/// summary fill datatable one(dt1)

Dim dt1 As New DataTable

dt1 = connection.LoadPoliceData("")

///摘要填充数据表1(dt2)

Dim dt2 As New DataTable

dt2 = connection.LoadDataCompare("")

///摘要声明数据表保存。我想要填充可枚举的数据

Dim save As New DataTable

save.Columns.Add(" Name",GetType(String))

save.Columns.Add(" Mobile",GetType(String))

///使用dt1和dt2的连接编写linq查询的摘要,以及数据表(保存)

Dim data1 =(来自datarow1在dt1.AsEnumerable中              加入datarow2在dt2.AsEnumerable中               在datarow1.Field(Of String)(" NameofPerson")等于datarow2.Field(Of String)(" Name")和datarow1.Field(Of String)(" Mobile& #34;)等于datarow2.Field(Of String)(" MobileNumber")               选择save.LoadDataRow(New Object(){datarow1.Field(Of String)(" NameofPerson"),datarow2.Field(Of String)(" MobileNumber")},False)) .Distinct()。ToList()

///数据表保存的摘要计数

Dim i = save.Rows.Count