Xavier W.
Xavier W.

Reputation: 1360

Getting the element missing in a second list of different type

I have two differents type of List :

List<class1> list1;
List<class2> list2;

Both entities have a same property called Id. list1 contains 10 elements and list2 has 200.

I need to get the list of element in list1 who are not in list2 according to the field Id.

I know there is a Linq operator called Except, but it is only for two elements of the same type and assume that all field of the entities are equals.

Upvotes: 1

Views: 279

Answers (2)

Anthony Pegram
Anthony Pegram

Reputation: 126854

The other answer presented will not scale well as the sizes of your lists grow. A simple change to make it more performant is to turn the exception list into a HashSet. If the Id property is an integer, it would look something like this:

var exceptIds = new HashSet<int>(list2.Select(y => y.Id).Distinct());
var unmatched = list1.Where(x => !exceptIds.Contains(x.Id)).ToList();
unmatched.Dump(); // LinqPad method, to see output

If the type of Id is something else, simply substitute it into the first line as the generic type parameter.

Alternately, you can produce the same unmatched output using a left join technique, much like a "find unmatched records" query in SQL.

var unmatched = (from item in list1
                join item2 in list2 on item.Id equals item2.Id into grp
                from x in grp.DefaultIfEmpty()
                where x == null
                select item).ToList();

Upvotes: 3

Slava Utesinov
Slava Utesinov

Reputation: 13488

What about this:

var exceptIds = list2.Select(y => y.Id).Distinct().ToList();
list1 = list1.Where(x => !exceptIds.Contains(x.Id)).ToList();

Upvotes: 1

Related Questions