Count number of element in List>

前端 未结 2 661
北荒
北荒 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<T>();
    foreach (var list in listOfLists)
    {
        foreach (var item in list)
        {
            set.Add(item);
        }
    }
    var result = set.Count;
    
    0 讨论(0)
  • 2021-02-12 08:30

    By using LINQ, I think your code is good with a bit changes that no need for .ToList(), just call Count() extension as the following:

    int result = listOfLists.SelectMany(list => list).Distinct().Count();
    
    0 讨论(0)
提交回复
热议问题