LINQ - Find all items in one list that aren't in another list

John Humphreys - w00te picture John Humphreys - w00te · Jul 10, 2012 · Viewed 73.4k times · Source

I'm stuck with a LINQ query (or any other efficient means of accomplishing the same thing). Can someone show me how I can select all the items in one list that are not present in another list?

Basically, I have a list I formed by matching items between two other lists. I need to find all the items in the first list that matches weren't found for. Can someone fill in the stars in the second LINQ query below with the query that would achieve this goal? If I were using TSQL, I would do SELECT * NOT IN (), but I don't think LINQ allows that.

//Create some sample lists.
List<IdentifierLookupData> list1 = new List<IdentifierLookupData> { /*Init */ };
List<IdentifierLookupData> list2 = new List<IdentifierLookupData> { /*Init */ };

//Find all items in list1 and list2 that match and store them in joinItems.
var joinItems = (from d1 in list1
    join d2 in list2 on d1 equals d2
    select d1).ToList<IdentiferLookupData>();

//Find all items in list1 not in joinItems.
var deletedItems = (from d1 in list1
     ***select all items not found in joinItems list.***

Answer

Dimitri picture Dimitri · Jul 10, 2012

Try using .Except extension method (docs):

var result = list1.Except(list2);

will give you all items in list1 that are not in list2.