vb.net 比较两个数据表并合并到新的数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22010467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare between two datatables and merge into new datatable
提问by Ashis Biswas
Suppose i have two data table contain same column name, But record may or may not be the same. My question is how to compare between two data table and marge into new one. example:
假设我有两个数据表包含相同的列名,但记录可能相同也可能不同。我的问题是如何比较两个数据表并将marge 转换为新的。例子:
datatable 1
数据表1
Name value A 1 B 2 C 3 D 4
datatable 2
数据表2
Name value A 9 B 2 D 1
New datatable(Compare based on datatable 1)
新建数据表(根据数据表1比较)
Name value(From1) value(From2) A 1 9 B 2 2 C 3 D 4 1
If a record present in datatable1is not present in datatable2then add blank. Here the datatable generate from XML. I am using vb.net 2008 express.
如果存在于中的记录datatable1不存在于中,datatable2则添加空白。这里的数据表从 XML 生成。我正在使用 vb.net 2008 express。
回答by sloth
Create a primary key on the Namecolumn. Then make sure the valuecolumns have different names (like value1and value2). Then simply use Merge():
在Name列上创建主键。然后确保value列具有不同的名称(如value1和value2)。然后简单地使用Merge():
Example:
例子:
Dim dt1 = New DataTable()
dt1.Columns.Add("Name", GetType(String))
dt1.Columns.Add("value1", GetType(Integer))
dt1.Rows.Add({"A", 1})
dt1.Rows.Add({"B", 2})
dt1.Rows.Add({"C", 3})
dt1.Rows.Add({"D", 4})
dt1.PrimaryKey = {dt1.Columns("Name")}
Dim dt2 = New DataTable()
dt2.Columns.Add("Name", GetType(String))
dt2.Columns.Add("value2", GetType(Integer))
dt2.Rows.Add({"A", 9})
dt2.Rows.Add({"B", 2})
dt2.Rows.Add({"D", 1})
dt2.PrimaryKey = {dt2.Columns("Name")}
dt1.Merge(dt2)
dt1now looks like:
dt1现在看起来像:


回答by Pragnesh Khalas
I Think below code will help you
我认为下面的代码会帮助你
'dtTable1 - First Table
'dtTable2 - Secound Table
'dtNewData - Result Table
Dim dtNewData As New DataTable
dtNewData = dtTable1.Copy()
dtNewData.PrimaryKey = New DataColumn() {dtNewData.Columns("Name")}
dtNewData.Columns.Add("Value2")
For Each dr As DataRow In dtTable2.Rows
If dtNewData.Rows.Contains(dr("Name")) = False Then
Dim dr1 As DataRow = dtNewData.NewRow
dr1("Name") = dr("Name")
dr1("Value2") = dr("Value")
dtNewData.Rows.Add(dr1)
Else
dtNewData.Rows.Find(dr("Name"))("Value2") = dr("Value")
End If
Next

