join unknown number of lists in linq

前端 未结 3 1127
青春惊慌失措
青春惊慌失措 2021-01-20 02:27

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

3条回答
  •  广开言路
    2021-01-20 02:51

    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 that you fill with the first list and intersect with with the remaining lists (as shown by @Servy).

    var intersection = new HashSet(listOfLists.First());
    
    foreach (List list in listOfLists.Skip(1))
    {
        intersection.IntersectWith(list);
    }
    

提交回复
热议问题