【问题标题】:Find differences in datatables with linq when datatables have different columns当数据表具有不同的列时,使用 linq 查找数据表中的差异
【发布时间】:2018-02-16 12:15:56
【问题描述】:

以下函数返回两个数据表的差异,但仅当两个表具有相同的列时才有效。

在我的情况下,列是不同的,但列是“dictkey”。我的两个数据表中都存在“dictkey”列。

我如何让它工作,我的函数只返回行,其中“dictkey”是不同的,无论其他列如何,都不存在。

 Public Function Check_Desparity(Byval dtTestStep as DataTable, Byval dtLimits as DataTable) as IEnumerable(Of DataRow)

    Dim diff = dtLimits.AsEnumerable.Except(dtTestSteps.AsEnumberable, DataRowComparer.Default)

    Return diff

    End Function

【问题讨论】:

  • 你需要自己实际编写一个循环。想想如果这是一个手动过程,你会怎么做。这就是你在代码中的做法。

标签: vb.net linq datatable


【解决方案1】:

您可以创建一个自定义IEqualityComparer,它只比较所需的列,并使用Except,它将IEqualityComparer 作为参数,或者您可以使用MoreLINQ 中的ExceptBy,或者您可以自己做@ 987654325@等价:

Public Function Check_Desparity(Byval dtTestSteps As DataTable, Byval dtLimits As DataTable) As IEnumerable(Of DataRow)
    Dim dtTestStepsHash As New HashSet(Of String)(dtTestSteps.AsEnumerable.Select(Function(dr) CType(dr("dictkey"), String)))
    Return dtLimits.AsEnumerable.Where(Function(dr) Not dtTestStepsHash.Contains(CType(dr("dictkey"),String)))
End Function

我假设列 dictkey 的类型为 String,但您可以输入正确的类型。

这相当于ExceptBy 操作。

函数中的第一行会创建一个 HashSet,其中包含您要从答案中排除的所有 "dictkey" 值,因为 HashSet 提供了高效(接近恒定)速度的 Contains 操作。

第二行返回 dtLimitsDataTable 中具有 "dictkey" 值但不包含在 dtTestSteps DataTable 中的那些行,这是通过检查每一行的 dtTestStepsHash 来确定的( dr) 并排除 HashSet 中的那些值。

【讨论】:

  • 这个解决方案有效,但我希望能有一个简短的解释,因为我不太明白。
  • @ManfredSinger 我添加了一个解释。如果不清楚,请告诉我!
  • 感谢您的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2013-01-20
  • 2011-01-25
  • 2013-07-12
相关资源
最近更新 更多