我想加入两个DataTable并从结果中创建第三个。结果DataTable应该有三列:
我的编译选项:
选项推断:关闭
Dim dr As DataRow
REM Dt1
Dim Dt1 As New DataTable
Dt1.Columns.Add("ID", GetType(Integer))
Dt1.Columns.Add("Name", GetType(String))
dr = Dt1.NewRow
dr("ID") = 1
dr("Name") = "Peter"
Dt1.Rows.Add(dr)
dr = Dt1.NewRow
dr("ID") = 2
dr("Name") = "Anna"
Dt1.Rows.Add(dr)
dr = Dt1.NewRow
dr("ID") = 3
dr("Name") = "John"
Dt1.Rows.Add(dr)
REM End Dt1
REM Dt2
Dim Dt2 As New DataTable
Dt2.Columns.Add("ID", GetType(Integer))
Dt2.Columns.Add("YearOfBirth", GetType(Integer))
dr = Dt2.NewRow
dr("ID") = 1
dr("YearOfBirth") = 1970
Dt2.Rows.Add(dr)
dr = Dt2.NewRow
dr("ID") = 2
dr("YearOfBirth") = 1980
Dt2.Rows.Add(dr)
REM End Dt2
Dim Dt3 As New DataTable
Dim query As IEnumerable(Of DataRow) = From dr1 In Dt1.AsEnumerable()
Group Join dr2 In Dt2.AsEnumerable()
On dr1.Field(Of Integer)("ID") Equals dr2.Field(Of Integer)("ID")
Into joined = Group
From j In joined.DefaultIfEmpty()
Select New With
{
.ID = dr1.Field(Of Integer)("ID"),
.Name = dr1.Field(Of String)("Name"),
.YearOfBirth = j.Field(Of Integer)("YearOfBirth")
}
Dt3 = query.CopyToDataTable
但是我在编辑器中得到了错误消息(VS 2017):
"错误BC36754: ' IEnumerable(匿名类型:ID为整数,名称为字符串,YearOfBirth为整数)'无法转换为IEnumerable(Of DataRow)'因为'匿名类型:ID为整数,名称为字符串,YearOfBirth为整数'不是根据' Out' DataRow'来源的。通用参数' T'在 接口IEnumerable(Of Out T)'。"
答案 0 :(得分:0)
Select New
未指定类名作为查询结果将返回匿名类型(如IEnumerable(Of AnonymousType)
)和CopyToDataTable()
抛出异常,因为IEnumerable(Of AnonymousType)
无法直接转换为{{ 1}}。
因此,您需要使用额外的IEnumerable(Of DataRow)
方法将匿名类型转换为DataRow
,该方法会迭代Select
内容,并使用DataTable.NewRow()
返回IEnumerable(Of AnonymousType)
(使用ready { {1}}包括作为结果集的列名称:
DataRow
参考: