我在vb.net中有2个DataTable。每个都由它自己的存储过程填充。表A包含第一列中的项目编号。表B还包含第一列中的项目编号。表A可能有许多具有相同项目编号的记录,但表B中每个项目编号总是只有一个记录。我想将表B中的数据附加到表A中的每个匹配记录。我该怎么做?
表A可能如下所示:
PROJECT#,QUANTITY
12345,100
12345,200
12345,300
表B可能如下所示:
PROJECT#,CUSTOMER
12345,ABC Inc.
我想合并两者来创建这样的东西:
PROJECT#,QUANTITY,CUSTOMER
12345,100,ABC Inc。
12345,200,ABC Inc。
12345,300,ABC Inc。
请帮忙!
答案 0 :(得分:3)
我建议使用LINQ方法,LINQ有一个可以处理这个的连接运算符。
From q In quantities _
Join c In customers On q.project Equals c.project _
Select Quantity = q, Customer = c
答案 1 :(得分:3)
这可能对您有所帮助,并且可能是半通用的,足以应用于其他情况。
这是一个函数,它将通过传入两个表来合并数据(根据您的示例),两个数组包含每个表所需的列名,以及用于连接表的键。
假设tblA是驱动表,查找tblB。
Sub Main()
Dim tbl As DataTable
Dim colsA() As String = {"ProjectNo", "Quantity"}
Dim colsB() As String = {"Customer"}
Dim sKey As String = "ProjectNo"
tbl = MergeData(tblA, tblB, colsA, colsB, sKey)
End Sub
Private Function MergeData(ByVal tblA As DataTable, ByVal tblB As DataTable, _
ByVal colsA() As String, ByVal colsB() As String, _
ByVal sKey As String) As DataTable
Dim tbl As DataTable
Dim col As DataColumn
Dim sColumnName As String
Dim row As DataRow
Dim newRow As DataRow
Dim dv As DataView
tbl = New DataTable
dv = tblB.DefaultView
For Each sColumnName In colsA
col = tblA.Columns(sColumnName)
tbl.Columns.Add(New DataColumn(col.ColumnName, col.DataType))
Next
For Each sColumnName In colsB
col = tblB.Columns(sColumnName)
tbl.Columns.Add(New DataColumn(col.ColumnName, col.DataType))
Next
For Each row In tblA.Rows
newRow = tbl.NewRow
For Each sColumnName In colsA
newRow(sColumnName) = row(sColumnName)
Next
dv.RowFilter = (sKey & " = " & row(sKey).ToString)
If dv.Count = 1 Then
For Each sColumnName In colsB
newRow(sColumnName) = dv(0).Item(sColumnName)
Next
End If
tbl.Rows.Add(newRow)
Next
Return tbl
End Function
答案 2 :(得分:0)
任何AsEnumerable都可以在LINQ中使用
var quantity = DataTable1()。AsEnumerable(); var customers = DataTable2()。AsEnumerable();
var result = from dtquanRow in quantities
join dtcustomers in customers
on dtquanRow.Field<string>("project") equals dtcustomers.Field<string>("project")
select new
{
project = dtquanRow.Field<string>("project"),
Quantity = dtquanRow.Field<string>("Quantity"),
Customer = dtquanRow.Field<string>("Customer")
};
moredetailed query and table to linq conversion
它对Chris Chilvers的进一步解释 从q在数量_ 加入c在客户关于q.project Equals c.project _ 选择Quantity = q,Customer = c