Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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));

Most efficient:

var set = new HashSet<T>(listA);
set.SymmetricExceptWith(listB);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top