在linq中加入未知数量的列表 [英] join unknown number of lists in linq
问题描述
我遇到的情况是我生成了许多包含整数值的列表.但是,这些列表的数量仅在运行时已知,并且结果列表中存在的整数必须存在于所有列表中.是否有将所有这些列表合并为一个列表的方法?
I have a situation where I have generated a number of lists which contain integer values. However, the number of these lists is only known at runtime, and integers present in the resulting list must exist in all lists. Is there a method of joining all of these lists into a single list?
即
List<int> l1 = {1, 2, 3, 4};
List<int> l2 = {2, 3, 5, 7, 9};
List<int> l3 = {3, 9, 10};
List<int> ln = {....};
结果列表应如下
List<int> r = {3};
linq或其他任何方法有可能吗?
Is this possible with linq or any other methods?
推荐答案
我假设您有一个List<List<int>>
,该数字包含可变数量的List<int>
.
I assume that you have a List<List<int>>
that holds a variable number of List<int>
.
您可以相交第一个列表与第二个列表 >
You can intersect the first list with the second list
var intersection = listOfLists[0].Intersect(listOfLists[1]);
然后将结果与第三个列表相交
and then intersect the result with the third list
intersection = intersection.Intersect(listOfLists[2]);
,依此类推,直到intersection
保留所有列表的交集.
and so on until intersection
holds the intersection of all lists.
intersection = intersection.Intersect(listOfLists[listOfLists.Count - 1]);
使用for
循环:
IEnumerable<int> intersection = listOfLists[0];
for (int i = 1; i < listOfLists.Count; i++)
{
intersection = intersection.Intersect(listOfLists[i]);
}
使用foreach
循环(如 @lazyberezovsky 所示):
IEnumerable<int> intersection = listOfLists.First();
foreach (List<int> list in listOfLists.Skip(1))
{
intersection = intersection.Intersect(list);
}
使用 Enumerable.Aggregate :
var intersection = listOfLists.Aggregate(Enumerable.Intersect);
如果顺序不重要,则还可以使用 HashSet< T> 填充第一个列表,并与相交其余列表(如 @Servy 所示).
If order is not important, then you can also use a HashSet<T> that you fill with the first list and intersect with with the remaining lists (as shown by @Servy).
var intersection = new HashSet<int>(listOfLists.First());
foreach (List<int> list in listOfLists.Skip(1))
{
intersection.IntersectWith(list);
}
这篇关于在linq中加入未知数量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!