Search code examples
c#winformssystem.data.datatable

Compare two DataTables and select the rows that are not present in second table


I have two DataTables and I want to select the rows from the first one which are not present in second one

For example:

Table A
  id   column
  1     data1
  2     data2
  3     data3
  4     data4

Table B
  id   column
  1     data10
  3     data30

I want the result to be:

Table C
  id    column
  2      data2
  4      data4

Solution

  • You can use Linq, especially Enumerable.Except helps to find id's in TableA that are not in TableB:

    var idsNotInB = TableA.AsEnumerable().Select(r => r.Field<int>("id"))
            .Except(TableB.AsEnumerable().Select(r => r.Field<int>("id")));
    DataTable TableC = (from row in TableA.AsEnumerable()
                       join id in idsNotInB 
                       on row.Field<int>("id") equals id
                       select row).CopyToDataTable();
    

    You can also use Where but it'll be less efficient:

    DataTable TableC = TableA.AsEnumerable()
        .Where(ra =>  !TableB.AsEnumerable()
                            .Any(rb => rb.Field<int>("id") == ra.Field<int>("id")))
        .CopyToDataTable();