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.
Here is first solution: DataTable table1= ds. Tables["table1"]; DataTable table2= ds. Tables["table2"]; var diff= table1.
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; }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With