Reputation: 113
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:
datatable 1
Name value A 1 B 2 C 3 D 4
datatable 2
Name value A 9 B 2 D 1
New datatable(Compare based on datatable 1)
Name value(From1) value(From2) A 1 9 B 2 2 C 3 D 4 1
If a record present in datatable1
is not present in datatable2
then add blank. Here the datatable generate from XML. I am using vb.net 2008 express.
Upvotes: 1
Views: 10707
Reputation: 101072
Create a primary key on the Name
column. Then make sure the value
columns have different names (like value1
and value2
). Then simply use 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)
dt1
now looks like:
Upvotes: 3
Reputation: 2898
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
Upvotes: 1