Search code examples
c#linqlistwhere-in

how to select elements that not intersec?


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.


Solution

  • 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.