Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
I was recently working on a piece of code that required merging 2 DataTables based on 2 columns, however the table that I was merging the results into, I need not add the row if the columns matched. After searching around the net for a while and not really finding anything very useful I decided to write my own.
Essentially we get 2 DataTable’s and loop through the first one. If we find the where column1 and column2 in the first table row match column1 and column2 in the second DataTable row the we delete the row in the second DataTable. Finally we merge the2 tables with t duplicates removed.
The magic essentially happens with DataTable.Select and DataTable.Merge
This code is C# .NET
//tables that will be merged
DataTable table1 = new DataTable();
DataTable table2 = new DataTable(); //duplicates will be removed
//columns used to store what is found in the row's column
string column1 = string.Empty;
string column2 = string.Empty;
// loop through the rows in the first table and if
// the columns are found on an item in the second
//table then remove it
foreach (DataRow row in table1.Rows)
{
//set the column variables to what is in the
//current row
column1 = row["column 1 Name"].ToString();
column2 = row["column 2 Name"].ToString();
//get an array of each of the rows that match
//the columns in the current row
DataRow[] duplicateRows = table2.Select("Section = '" +
column1 + "' AND Subsection = '" + column2 + "'");
//loop through and remove each of the rows in the
//table that are duplicates
foreach (DataRow duplicateRow in duplicateRows)
table2.Rows.Remove(duplicateRow);
}
//merge the tables so that we now have 1
table1.Merge(table2);
Remember Me