我有两个需要合并的DataTable。两个表中都有一个名为" Code"基本上,如果一个表具有某个代码,它会与另一个表中的相应代码合并,将这些行值合并到其中。我会说它喜欢在SQL中使用内连接将两个表合并在一起。
请在vb.net中访问!
答案 0 :(得分:3)
以下是此answer的VB转换。
Dim dt1 As New DataTable()
dt1.Columns.Add("CustID", GetType(Integer))
dt1.Columns.Add("ColX", GetType(Integer))
dt1.Columns.Add("ColY", GetType(Integer))
Dim dt2 As New DataTable()
dt2.Columns.Add("CustID", GetType(Integer))
dt2.Columns.Add("ColZ", GetType(Integer))
For i As Integer = 1 To 5
Dim row As DataRow = dt1.NewRow()
row("CustID") = i
row("ColX") = 10 + i
row("ColY") = 20 + i
dt1.Rows.Add(row)
row = dt2.NewRow()
row("CustID") = i
row("ColZ") = 30 + i
dt2.Rows.Add(row)
Next
Dim results = From table1 In dt1.AsEnumerable()Join table2 In dt2.AsEnumerable() On CInt(table1("CustID")) = CInt(table2("CustID"))New With { _
Key .CustID = CInt(table1("CustID")), _
Key .ColX = CInt(table1("ColX")), _
Key .ColY = CInt(table1("ColY")), _
Key .ColZ = CInt(table2("ColZ")) _
}
For Each item As var In results
Console.WriteLine([String].Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ))
Next
Console.ReadLine()