使用 LINQ 查找非交集数据集

20
List<int> a = 1,2,3
List<int> b = 2,4,5

output
1,3,4,5

输出中是否应该包含3? - Dave
我猜是的...那应该在非交叉数据中。 - Reed Copsey
1
这里有一个更好的答案:https://dev59.com/9W035IYBdhLWcg3wGMHa - Amicable
3个回答

42

关键是使用 Except 函数得到两个列表的交集。

这将给出不相交元素的列表:

var nonIntersecting = a.Union(b).Except(a.Intersect(b));

我测试了一个简单的集合,但它不起作用。尽管这个解决方案在原帖中由@Amicable提出是有效的:https://dev59.com/9W035IYBdhLWcg3wGMHa - StackHola

4

经过验证和测试:

List<int> a = new List<int>(){1, 2, 3};
List<int> b = new List<int>(){2, 4, 5};


List<int> c = a.Except(b).Union(b.Except(a)).ToList();

我想要找到不相交的部分。 - ssl
Reed Copsey的回答更好! - Mitch Wheat

0

另一种方式:

List<int> a = new List<int> { 1, 2, 3 };
List<int> b = new List<int> { 2, 4, 5 };
var nonIntersecting = a.Union(b)
    .Where(x => !a.Contains(x) || !b.Contains(x));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接