0

If I have two list and I want the elements that are common in both lists, I can use this code:

var listC = listA.Intersect(listB);

However, If I want the elements that are not common? And without duplicates? is possible with intersect?

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

3 Answers3

3

Neither answer so far will include items from listB that aren't in listA. To get any item that is in either list, but is not in both lists:

listA.Union(listB).Except(listA.Intersect(listB));
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
1

Yep, that's possible. It's called Enumerable.Except.

Use this:

var result = listA.Except(listB); //maybe a .ToList() at the end,
//or passing an IEqualityComparer<T> if you want a different equality comparison.
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
1

Most efficient:

var set = new HashSet<T>(listA);
set.SymmetricExceptWith(listB);
lisp
  • 4,138
  • 2
  • 26
  • 43