【发布时间】:2010-07-07 03:57:24
【问题描述】:
我正在尝试寻找与 LINQ 的交集。
示例:
List<int> int1 = new List<int>() { 1,2 };
List<int> int2 = new List<int>();
List<int> int3 = new List<int>() { 1 };
List<int> int4 = new List<int>() { 1, 2 };
List<int> int5 = new List<int>() { 1 };
想要返回:1,因为它存在于所有列表中。如果我运行:
var intResult= int1
.Intersect(int2)
.Intersect(int3)
.Intersect(int4)
.Intersect(int5).ToList();
它什么也不返回,因为 1 显然不在 int2 列表中。无论一个列表是否为空,我如何让它工作?
使用上面的例子或:
List<int> int1 = new List<int>() { 1,2 };
List<int> int2 = new List<int>();
List<int> int3 = new List<int>();
List<int> int4 = new List<int>();
List<int> int5 = new List<int>();
在这种情况下我如何返回 1 和 2.. 我不知道列表是否已填充...
【问题讨论】:
-
考虑
{1}, {2}, {3}的交集。在与前两个相交之后,您将尝试找到{}, {3}的交集。你要求我们想出一些东西,在这种情况下会给{},但如果我们对{3}, {}执行相同的操作,{3}。如果您不想考虑空列表,请在尝试计算交集之前将它们从考虑中删除。 -
@Anon,有趣的观察。
-
我将如何管理? if (int2.Count >0) var set = int1.Intersect(int2); if (int3.Count >0) var set2 = set.Intersect(set); if (int2.Count >0) var set3 = int2.Intersect(int2); .....似乎有点胡作非为......
-
他的意思是{1}和{2}的交集是一个空列表,所以that和{3}的交集是{3} .这是允许 Intersect 方法忽略空集的一个陷阱,因为空的 results 会被忽略以及链接方法。
-
那么问题来了……难道没有办法忽略空集而不检查它们是否为空吗?