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.
到目前为止,这两个答案都不会包括listB
不在listA
. 要获取任一列表中但不在两个列表中的任何项目:
listA.Union(listB).Except(listA.Intersect(listB));
最高效:
var set = new HashSet<T>(listA);
set.SymmetricExceptWith(listB);
是的,这是可能的。它被称为Enumerable.Except。
用这个:
var result = listA.Except(listB); //maybe a .ToList() at the end,
//or passing an IEqualityComparer<T> if you want a different equality comparison.