C# Linq with datatables – select from one table what does not exist in the other

clinq

For example, I have two tables that look like this

DATATABLE 1

COLA  |  COLB  |  COLC 
 1       123      321
 2       321      333
 3       222      232

DATATABLE 2

COLA  |  COLB  |  COLC 
 1       123      321
 2       321      333

I want to select only row 3 from table one.

I want to be able to join the two tables together on the COLA ID, but then only select the rows from DATATABLE 1 that do noto exist in DATATABLE 2.

How can I do this in LINQ?

I would strongly prefer the results to be a datatable, or Ienumerable or something easy to change back into a datatable. if it's not possible i will manage.

Best Answer

var rows = from t1 in table1.AsEnumerable()
           join t2 in table2.AsEnumerable() 
               on t1.Field<int>("COLA") equals t2.Field<int>("COLA") into tg
           from tcheck in tg.DefaultIfEmpty()
           where tcheck == null
           select t1

This ultimately performs a left outer join, and any rows from table2 that are null means the record in table1 doesn't have a match. I would recommend against using the Any method, as it could possibly enumerate table2 for every row in table1 (which for larger sets, this is bad). LINQ Join will enumerate both tables only once in order to find the matching pairs for the selector function you specify.