Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 dataTables

Tags:

c#

.net

datatable

I have 2 datatables and I just want to know if they are the same or not. By "the same", I mean do they have exactly the same number of rows with exactly the same data in each column, or not. I'd love to write (find) a method which accepts both tables and returns a boolean.

How can I compare 2 datatables in this way? Both have identical schemas.

like image 911
MAW74656 Avatar asked Sep 22 '11 16:09

MAW74656


People also ask

How can I get the difference between two Datatables in C#?

Here is first solution: DataTable table1= ds. Tables["table1"]; DataTable table2= ds. Tables["table2"]; var diff= table1.


2 Answers

 public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)  {     if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)                 return false;       for ( int i = 0; i < tbl1.Rows.Count; i++)     {         for ( int c = 0; c < tbl1.Columns.Count; c++)         {             if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))                         return false;         }      }      return true;   } 
like image 151
Nick Rolando Avatar answered Sep 29 '22 17:09

Nick Rolando


If you were returning a DataTable as a function you could:

DataTable dataTable1; // Load with data DataTable dataTable2; // Load with data (same schema)  // Fast check for row count equality. if ( dataTable1.Rows.Count != dataTable2.Rows.Count) {     return true; }  var differences =     dataTable1.AsEnumerable().Except(dataTable2.AsEnumerable(),                                             DataRowComparer.Default);  return differences.Any() ? differences.CopyToDataTable() : new DataTable(); 
like image 21
samneric Avatar answered Sep 29 '22 15:09

samneric