如何选择不相交的元素
本文关键字:元素 何选择 选择 | 更新日期: 2023-09-27 18:17:39
如果我有两个列表,并且我想要两个列表中共有的元素,我可以使用下面的代码:
var listC = listA.Intersect(listB);
然而,如果我想要不常见的元素?没有副本吗?是可能的吗?
谢谢。
到目前为止,这两个答案都不包括listB
中不属于listA
的项目。获取任何项,该项在一个列表中,但不在两个列表中:
listA.Union(listB).Except(listA.Intersect(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.
最高效:
var set = new HashSet<T>(listA);
set.SymmetricExceptWith(listB);