我有两个DataTable dt_original和dt_updated。我想将它们合并在一起 有条件的话,只有当dt_updated与dt_orignal具有相同的item_id时,如何合并行?
dt_original: -
item_id|item_name|qty|unitprice|col1|col2|col3|
===============================================
1 |apple |5 |1.00 |xxx |xxx |xxx |
2 |orange |10 |2.00 |xxx |xxx |xxx |
dt_updated: -
item_id|item_name|qty|
======================
1 |apple |2 |
我想要的结果: -
item_id|item_name|qty|unitprice|col1|col2|col3|
===============================================
1 |apple |2 |1.00 |xxx |xxx |xxx |
mycode的:
Dim dt_original As DataTable = Model_Query(str_tableControl1)
Dim dt_result As DataTable
dt_original.PrimaryKey = New DataColumn() {dt_original.Columns("item_id")}
dt_updated.PrimaryKey = New DataColumn() {dt_updated.Columns("item_id")}
dt_original.Merge(dt_updated)
dt_result = dt_original
MyResult: -
item_id|item_name|qty|unitprice|col1|col2|col3|
===============================================
1 |apple |2 |1.00 |xxx |xxx |xxx |
2 |orange |10 |2.00 |xxx |xxx |xxx |
那么如何解决这个问题?
答案 0 :(得分:3)
您想要更新数量字段吗?我会使用LINQ和循环:
Dim updatedRows = From rowOriginal In dt_original.AsEnumerable()
Join rowUpdated In dt_updated.AsEnumerable()
On rowOriginal.Field(Of Int32)("item_id") Equals rowUpdated.Field(Of Int32)("item_id")
Dim dt_result As DataTable = dt_original.Clone() ' empty table, same columns
For Each x In updatedRows
dt_result.ImportRow(x.rowOriginal)
dt_result.Rows(dt_result.Rows.Count-1).SetField("qty", x.rowUpdated.Field(of int32)("qty"))
Next
如果您想更新原始表格,那就更容易了:
For Each x In updatedRows
x.rowOriginal.SetField("qty", x.rowUpdated.Field(of int32)("qty"))
Next