我有以下代码。
Dim hardlimit As DataTable = From f In dealDataTable.AsEnumerable
Join f2 In hardlimithit.AsEnumerable
On f.Field(Of Integer)("dea_ID") Equals f2.Field(Of Integer)("ID")
Select f
我试图从" dealDataTable"中选择获取所有数据。其中id与我的其他数据表的id字段匹配。
我从此代码中收到此错误。
System.InvalidCastException was caught
HResult=-2147467262
Message=Unable to cast object of type '<JoinIterator>d__61`4[System.Data.DataRow,System.Data.DataRow,System.Int32,System.Data.DataRow]' to type 'System.Data.DataTable'.
Source=FMSOvernight
StackTrace:
at FMSOvernight.Module1.RunLimitCalculations() in C:\Cloud Source Control\Funding Management Overnighter\FundingManagementSystemOvernightRoutine\Module1.vb:line 273
at FMSOvernight.Module1.StartGeneration() in C:\Cloud Source Control\Funding Management Overnighter\FundingManagementSystemOvernightRoutine\Module1.vb:line 135
InnerException:
答案 0 :(得分:1)
您选择IEnumerable<DataRow>
行,而不是DataTable
。您可以使用CopyToDataTable
:
Dim hardlimitRows = From f In dealDataTable.AsEnumerable
Join f2 In hardlimithit.AsEnumerable
On f.Field(Of Integer)("dea_ID") Equals f2.Field(Of Integer)("ID")
Select f
Dim hardlimitTable = hardlimitRows.CopyToDataTable()
但请注意,如果没有行,此方法将抛出InvalidOperationException
。你必须先检查一下。例如:
Dim hardlimitTable As DataTable = dealDataTable.Clone() ' empty table with the same columns '
If hardlimitRows.Any() Then
hardlimitTable = hardlimitRows.CopyToDataTable()
End If