问题描述
我试图找到一个LINQ相交
I'm trying to find an intersect with 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,因为它所有列表中存在的..如果我运行:
Want to return: 1 as it exists in all lists.. If I run:
var intResult= int1
.Intersect(int2)
.Intersect(int3)
.Intersect(int4)
.Intersect(int5).ToList();
它返回毫无作为1显然不是在INT2列表。我怎么不管这个工作,如果一个列表为空或不?
It returns nothing as 1 obviously isn't in the int2 list. How do I get this to work regardless if one list is empty or not ?
使用上面的例子或:
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在这种情况下..我不知道提前时间,如果列表填充...
How do I return 1 & 2 in this case.. I don't know ahead of time if the lists are populated...
推荐答案
如果您需要它在一个单一的步骤,最简单的办法是过滤掉空列表:
If you need it in a single step, the simplest solution is to filter out empty lists:
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));
}
您可以使用它在列表或其他<$ C $的集合C>的IEnumerable 取值:
You can then use it on a collection of lists or other IEnumerable
s:
IEnumerable<int>[] lists = new[] { l1, l2, l3, l4, l5 };
var intersect = lists.IntersectNonEmpty();
您可能更喜欢常规的静态方法:
You may prefer a regular static method:
public static IEnumerable<T> IntersectNonEmpty<T>(params IEnumerable<T>[] lists)
{
return lists.IntersectNonEmpty();
}
var intersect = ListsExtensionMethods.IntersectNonEmpty(l1, l2, l3, l4, l5);
这篇关于LINQ相交,多个列表,一些空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!