【问题标题】:Error joining two datatables in linq在 linq 中连接两个数据表时出错
【发布时间】:2015-11-24 14:12:49
【问题描述】:

我有以下代码。

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: 

【问题讨论】:

    标签: vb.net linq join


    【解决方案1】:

    您正在选择行,所以IEnumerable&lt;DataRow&gt;,这不是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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多