Count number of element in List>

前端 未结 4 1308
野性不改
野性不改 2021-02-12 07:53

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

4条回答
  •  渐次进展
    2021-02-12 08:51

    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;
    

提交回复
热议问题