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 i
I assume that you have a List
that holds a variable number of >
List
.
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]);
and so on until intersection
holds the intersection of all lists.
intersection = intersection.Intersect(listOfLists[listOfLists.Count - 1]);
Using a for
loop:
IEnumerable intersection = listOfLists[0];
for (int i = 1; i < listOfLists.Count; i++)
{
intersection = intersection.Intersect(listOfLists[i]);
}
Using a foreach
loop (as shown by @lazyberezovsky):
IEnumerable intersection = listOfLists.First();
foreach (List list in listOfLists.Skip(1))
{
intersection = intersection.Intersect(list);
}
Using Enumerable.Aggregate:
var intersection = listOfLists.Aggregate(Enumerable.Intersect);
If order is not important, then you can also use a HashSet
var intersection = new HashSet(listOfLists.First());
foreach (List list in listOfLists.Skip(1))
{
intersection.IntersectWith(list);
}