Thursday, December 18, 2008

Linq Where not exists query

Today I needed a where not exists query in my linq to objects.

Fortunatly I found it using the google :)

Suppose we have 2 lists, the first of a dummy class with properties Id and Name, the second of another dummy class with properties Id and Color (just so they are different)

We can perform a 'where not exists' query as follows :

var OnlyInFirstQuery = (from item1 in list1 select item1.Id)
.Except
(from item2 in list2 join list1Item in list1 on list2.Id equals list1Item.Id select item2.Id);


This will give us a list having only the items in list1 that do not exist in list2, just as I needed.