【问题标题】:VB.NET LINQ join Distinct 2 tablesVB.NET LINQ 连接不同的 2 个表
【发布时间】:2012-12-11 05:00:05
【问题描述】:

我有 2 个数据表,它们具有相同的列但具有不同的数据,并且有时有些行共享相同的 ID

我想将那些表加入到表 2 中某些行的 ID 在表 1 中不存在的表中

so if i the following tables
ID Name
1  A
2  B
3  C

ID Name
5  D
1  A
2  B
3  C

the from joining would be

ID Name
1  A
2  B
3  C
5  D

这是我尝试过的

 Dim q = From e In tbl1.AsEnumerable Join r In tbl2.AsEnumerable On e.Field(Of Integer)("id") Equals r.Field(Of Integer)("id")

但不知道如何将其保存到数据表中

【问题讨论】:

  • @MitchWheat 用我的代码更新问题
  • 似乎 UNION 可能是更好的选择。 msdn.microsoft.com/en-us/library/bb341731.aspx
  • @MitchWheat 但我仍然使用 AsEnumerable 并使用 union 或 join,如何将数据转换回数据表?!
  • 这取决于您的数据源提供者。
  • 您是否需要以DataTable 的形式返回数据?有时IEnumerable<T> 会给你更好的性能和减少内存占用。您可以使用 LINQ 轻松地从表中提取数据,并对 IEnumerable 对象执行UNION

标签: vb.net linq join distinct union


【解决方案1】:

LINQ 在使用 DataTable 时并不是那么好,但您可以这样做:

Dim diff = tbl2.AsEnumerable().Except(tbl1.AsEnumerable(), New DataRowComparer())

Dim tbl = tbl1.Copy()
For Each dataRow As DataRow In diff
    tbl.ImportRow(dataRow)
Next

您需要创建一个IEqualityComparer 来定义如何比较DataRows。我决定只比较它们的 Id 值,但您可以以类似的方式比较每一列:

Public Class DataRowComparer
    Implements IEqualityComparer(Of DataRow)

    Public Function Equals(ByVal x As DataRow, ByVal y As DataRow) As Boolean Implements IEqualityComparer(Of DataRow).Equals
        Return CInt(x("Id")) = CInt(y("Id"))
    End Function

    Public Function GetHashCode(ByVal obj As DataRow) As Integer Implements IEqualityComparer(Of DataRow).GetHashCode
        Return CInt(obj("Id")).GetHashCode()
    End Function
End Class

【讨论】:

  • 实际上,我认为 LINQ 非常适合与 DataTable 一起工作。提供的方法为您提供了处理 POD 的所有能力。您遇到了哪些问题?
  • @MauriceReeves 我记得它适用于IEnumerable,如果您需要DataTable 中的结果,则需要额外的工作。 DataTable 没有 ToListToArray 等效项。
  • 知道了。我的意思是,我看它的方式,调用ToEnumerable() 然后迭代行、过滤、使用谓词等是相当轻松的。在某些情况下我不使用它,例如如果我只需要一次访问一组数据,我可能会放弃 IEnumerable 并直接使用该表,但此时,任何迭代,特别是如果我需要加入其他数据集,我喜欢通过 LINQ 进行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多