Pregunta

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.

¿Fue útil?

Solución 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.

Otros consejos

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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top