Count number of element in List>

前端 未结 2 664
北荒
北荒 2021-02-12 08:19

I have a List>. How can I count all the elements in this as if it was a single List in the fastest way?

So far I h

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-12 08:30

    I would recommend a simple, nested loop with a HashSet if you need to eliminate duplicates between lists. It combines the SelectMany and Distinct operations into the set insertion logic and should be faster since the HashSet has O(1) lookup time. Internally Distinct() may actually use something similar, but this omits the construction of the single list entirely.

    var set = new HashSet();
    foreach (var list in listOfLists)
    {
        foreach (var item in list)
        {
            set.Add(item);
        }
    }
    var result = set.Count;
    

提交回复
热议问题