0

I have two DataTables that have both the same schema (same columns names and types) .I want to get the rows that appear in the first and not in the second one. Could anyone help me in this? Thanks.

SharpC
  • 6,974
  • 4
  • 45
  • 40

3 Answers3

1

Thankfully, MS has created extension methods for DataTable that let you use Linq methods (like Except) to query data rows, and written a class that implements IEqualityComparer<DataRow> that compares DataRow instances by their column values:

var rows = dt1.AsEnumerable()
              .Except(dt2.AsEnumerable(),DataRowComparer.Default);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

I would write something like this:

var onlyIn1 = dataTable1.Where( row1 => !dataTable2.Rows.Any( row2 => row1["CustomerKey"] == row2["CustomerKey"]) ).ToList();
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447
0

You could try this:

var onlyIn1 = db.Table1.Except(db.Table2).ToList();

I never test this, but it should work like T-SQL's EXCEPT

Eric
  • 3,165
  • 1
  • 19
  • 25