Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Lambda - Find all ID's in one list that don't exist in another list

Tags:

lambda

linq

I have two collections of objects (List list1 and List list2). There is a property on each called "ID". I know that list2 will always have more items than list1, I just need an easy way to get a collection of all the items that exist in list2 but not list1 using LINQ lambda expressions.

like image 864
Hungry Beast Avatar asked Sep 30 '10 23:09

Hungry Beast


2 Answers

If you only need the IDs of the items then Mark's answer will do the trick nicely. If you need to return the items themselves (and they don't already have a suitable Equals implementation) then you could try something like this:

// assumes that the ID property is an int - change the generic type if it's not
var ids = new HashSet<int>(list1.Select(x => x.ID));
var results = list2.Where(x => !ids.Contains(x.ID));
like image 138
LukeH Avatar answered Nov 06 '22 07:11

LukeH


This will get you the IDs that are only in list2:

var ids = list2.Select(x => x.Id).Except(list1.Select(x => x.Id));

If your objects compare equal when they have the same ID then you can simplify it to:

var objects = list2.Except(list1);
like image 23
Mark Byers Avatar answered Nov 06 '22 09:11

Mark Byers