I have the following scenario:
Table A that has 50 records and Table B that has 2 records.
I need to define a new table, say TableDiff which should contain 48 records from Table A that doesn't exist in Table B
My problem is that Table A and Table B are not identical but I have the field rowId
which exists in both tables that I need to compare using it.
One way using Enumerable.Except
and Enumerable.Join
:
var aIDs = TableA.AsEnumerable().Select(r => r.Field<int>("RowID"));
var bIDs = TableB.AsEnumerable().Select(r => r.Field<int>("RowID"));
var diff = aIDs.Except(bIDs);
DataTable tblDiff = (from r in TableA.AsEnumerable()
join dId in diff on r.Field<int>("RowID") equals dId
select r).CopyToDataTable();
Here's the linq-to-objects "left-join"-approach:
DataTable tblDiff = (from rA in TableA.AsEnumerable()
join rB in TableB.AsEnumerable()
on rA.Field<int>("RowID") equals rB.Field<int>("RowID") into joinedRows
from ab in joinedRows.DefaultIfEmpty()
where ab == null
select rA).CopyToDataTable();