我有2个数据表表,它们具有相同的列,但具有不同的数据,有时候共享的行具有相同的ID
我想将那些连接到table1中某些行的ID在table1中不存在的表
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")
但不知道如何将其转换为数据表
答案 0 :(得分: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
来定义如何比较DataRow
。我决定只比较他们的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