【问题标题】:Compare two datatables in vb.net比较 vb.net 中的两个数据表
【发布时间】:2020-07-11 17:57:42
【问题描述】:

DataTable One 只包含一列(代码)

Code
3
7

而且第二个数据表也只包含一列(ProductCode)

ProductCode
2
3
6
7

我想使用最佳技术比较第一个数据表的所有值是否存在于第二个数据表中。目前我正在使用,但一次是 FALSE,第二次是 TRUE,所以看起来不实用。

Applicable = False
For Each chkRow As DataRow In chk.Rows
   For Each dtRow As DataRow In dt.Rows
      If chkRow("ProductCode") = dtRow("Code") Then
         Applicable = True
         Exit For
       Else
         Applicable = False
       End If
    Next
Next

请提出更好的解决方案。

【问题讨论】:

  • 您的问题已经回滚到原来的版本,已经有了答案。如此大刀阔斧的修改改变了原来的问题太多,你应该考虑创建一个新问题。

标签: vb.net linq datatable


【解决方案1】:

我倾向于使用 LINQ 查询:

Dim codes = table1.AsEnumerable().
                   Select(Function(row) row.Field(Of Integer)("Code"))
Dim productCodes = table2.AsEnumerable().
                          Select(Function(row) row.Field(Of Integer)("ProductCode")).
                          ToArray()

If codes.All(Function(code) productCodes.Contains(code)) Then
    '...
End If

请注意,productCodes 有一个 ToArray 调用,但 codes 没有。这是因为 productCodes 需要多次枚举,而您不想在延迟查询中这样做。

【讨论】:

  • @abdullah,宣布吧。
  • @abdullah,看来我最初为 Lambda 参数使用了错误的名称,但 @Jimi 为我们友好地编辑了它。这就是我直接在答案中输入代码而不是在 IDE 中然后复制/粘贴的结果。我还在If 语句中添加了一个缺少的右括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多