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.
Asked
Active
Viewed 652 times
0
-
You could use Linq's Except. You would probably have to provide your own EqualityComparer. – Crowcoder Jun 16 '16 at 16:55
-
https://stackoverflow.com/questions/7560742/difference-between-2-datatable – William Xifaras Jun 16 '16 at 16:55
-
@WilliamXifaras the answer in the question you refer to is not working: it returns the rows that are in both DataTables. – Imededdine Fargi Jun 16 '16 at 17:11
3 Answers
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