I have a List<List<T>>.
How can I count all the elements in this as if it was a single List<T> in the fastest way?
So far I have used
List<int> result = listOfLists
.SelectMany(list => list)
.Distinct()
.ToList().Count;
but this actually creates a list and then counts the element which is not a very good idea.
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.