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.
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
Len() Method There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.
Use the list. count() method of the built-in list class to get the number of occurrences of an item in the given list.
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();
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With