Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of element in List<List<T>>

Tags:

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.

like image 621
kasperhj Avatar asked Jun 01 '11 12:06

kasperhj


People also ask

How do you count the number of elements in a list?

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.

How do you count the number of elements in a list in Python?

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.

How can I count the occurrences of a list item C#?

Use the list. count() method of the built-in list class to get the number of occurrences of an item in the given list.


2 Answers

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(); 
like image 171
Homam Avatar answered Oct 02 '22 12:10

Homam


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; 
like image 20
tvanfosson Avatar answered Oct 02 '22 11:10

tvanfosson