Get the differences between two data tables.

public Data.DataTable GetDifferencesBetweenTwoTables(Data.DataTable DataTable1, Data.DataTable DataTable2)
{
 Debug.WriteLine("Looking for changed records.");
 Debug.WriteLine("This function will compare two data tables and return a data table with the changed rows.");
 Debug.WriteLine("The two tables must have the same columns and at least one key column.");
 //Create an empty table with the correct fields to return the differences.
 Data.DataTable ModifiedDataTable = DataTable1.Clone;
 //Create an array to store the names of the key columns.
 string[] KeyColumnNames = new string[DataTable1.PrimaryKey.Length];
 //Get the key column names from the first table.
 for (int I = 0; I <= DataTable1.PrimaryKey.Length - 1; I++) {
  KeyColumnNames(I) = DataTable1.PrimaryKey(I).ColumnName;
 }
 //Look at each row in the second table.
 foreach (Data.DataRow RowInTable2 in DataTable2.Rows) {
  //Create a flag to record if the rows are different or not.
  bool RowChanged = false;
  //Create an array to store the key values.
  string[] RowKeys = new string[KeyColumnNames.Length];
  //Get the key values from the current row in the second table.
  for (int I = 0; I <= RowKeys.Length - 1; I++) {
   RowKeys(I) = RowInTable2.Item(KeyColumnNames(I));
  }
  //Look for a row in the first table that matches the current row in the second table.
  Data.DataRow RowInTable1 = DataTable1.Rows.Find(RowKeys);
  //If a match was found...
  if (RowInTable1 != null) {
   //Look at each column.
   foreach (Data.DataColumn ColumnInTable1 in DataTable1.Columns) {
    //Get the column number
    int ColumnIndex = ColumnInTable1.Ordinal;
    //Figure out what type of data is in the column.
    Type ColumnType = ColumnInTable1.DataType;
    //Compair the cell of this column in both of the rows to see if they match.
    //The cells must be converted to the correct type before comparison because nulls will cause it to fail.
    if (Convert.ChangeType(RowInTable1.Item(ColumnIndex), ColumnType) != Convert.ChangeType(RowInTable2.Item(ColumnIndex), ColumnType)) {
     //The cells do not match, so flag the change.
     RowChanged = true;
     //No use looking at the rest of the cells, so leave the for/next loop.
     break; // TODO: might not be correct. Was : Exit For
    }
   }
  } else {
   //The row in the second table does not exist in the first table so add this row to the table of modified rows.
   RowChanged = true;
  }
  if (RowChanged == true) {
   //Something in the current row was changed, so add it to the table to be returned by this function.
   ModifiedDataTable.Rows.Add(RowInTable2.ItemArray);
  }
 }
 Debug.WriteLine(ModifiedDataTable.Rows.Count + " records were changed.");
 return ModifiedDataTable;
}

No comments:

Post a Comment