0

I have a task which I think can be solved with LINQ. The problem is I am pretty new with it and I just can't implement my idea correctly.



Problem:
I have two string lists:

 var list1 = new List<string>{ "item1", "item2" }; <br>
 var list2 = new List<string>{ "item1", "item3", "item3", "item4" };

The goal is to return a new List containing the elements from list2 which are not contained in list1, ( "item3", "item4" )

Gicu Mironica
  • 585
  • 8
  • 22

1 Answers1

5

You're right, it is a simple one:

list2.Except(list1).ToList();

The trailing ToList is present because you said you goal is to return a new List - but if all you'll do is e.g. enumerate the result with a foreach or something, it can be omitted

Good spot from juharr; your first duplicated item3 was right on the word wrap boundary on the mobile site so I didn't notice your list was 1,3,3,4

A poorly performing variant that keeps duplicates, ok for small lists:

list2.Where(e => !list1.Contains(e));

A better performing version that should be used for large list1:

var lookup = new HashSet<string>(list1);
list2.Where(e => !lookup.Contains(e));
Caius Jard
  • 72,509
  • 5
  • 49
  • 80