我正在尝试寻找与 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。我不知道列表是否已填充...
最佳答案
如果您需要一步完成,最简单的解决方案是过滤掉空列表:
public static IEnumerable<T> IntersectNonEmpty<T>(this IEnumerable<IEnumerable<T>> lists)
{
var nonEmptyLists = lists.Where(l => l.Any());
return nonEmptyLists.Aggregate((l1, l2) => l1.Intersect(l2));
}
然后您可以在列表集合或其他 IEnumerable
上使用它:
IEnumerable<int>[] lists = new[] { l1, l2, l3, l4, l5 };
var intersect = lists.IntersectNonEmpty();
您可能更喜欢常规的静态方法:
public static IEnumerable<T> IntersectNonEmpty<T>(params IEnumerable<T>[] lists)
{
return lists.IntersectNonEmpty();
}
var intersect = ListsExtensionMethods.IntersectNonEmpty(l1, l2, l3, l4, l5);
关于c# - LINQ 相交,多个列表,一些为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3191810/