Blog Home  Home |  Breeze Home RSS 2.0 Atom 1.0 CDF  
SCAREY Sharepoint Blog - Merge 2 DataTables removing results that have 1 or more identical columns
Shannon - Breeze Training
# Tuesday, November 17, 2009

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);
Tuesday, November 17, 2009 11:09:53 AM (AUS Eastern Daylight Time, UTC+11:00)  #    Comments [0]    | 
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview
Copyright © 2010 Breeze Training. All rights reserved.