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]);
and so on until intersection
holds the intersection of all lists.
intersection = intersection.Intersect(listOfLists[listOfLists.Count - 1]);
Using a for
loop:
IEnumerable<int> 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<int> intersection = listOfLists.First();
foreach (List<int> 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<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);
}