Difference between two Entity Set using LINQ

By | March 29, 2011

In this tips I have discussed about how to get the difference between two table/ entity sets. As for example we want to get rows form table_A which are not exists in table_B. (When table_A primarykey is part of table_B foreignkey).

Following is way to get the row(s) form table_A which are not part of table_B

SELECT  
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL

In Linq to Sql you can achieve same thing just by calling one function Except.

var infoQuery =
(from tblA in db.Table_A
select tblA.Key)
.Except
(from tblB in db.Table_B
select tblB.Key);

So by using above query you can easily achieve task of getting difference between set of collection.