Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Count() of an IEnumerable be avoided?

In general, I am using a List and then returning them as IEnumerable when I no longer need to update them.

However, I ran into an issue where I actually need to enumerate through them but first need to know the count.

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

Also, what if the IEnumerable is the result of a LINQ query?

like image 700
LearningJrDev Avatar asked Aug 04 '15 17:08

LearningJrDev


People also ask

How do you count in IEnumerable?

IEnumerable has not Count function or property. To get this, you can store count variable (with foreach, for example) or solve using Linq to get count.

Is any or count faster C#?

Any() is ALWAYS faster than . Count() > 0 ).

Which is faster count or any?

First, Any() without parameters is quicker than Count() as it does not iterate through the whole collection. Second, Any() improves the readability of your code, indicating that the developer just wants to check if there are any items in the collection and isn't concerned with the exact number of items.

How do I know if IEnumerable has an item?

IEnumerable. Any() will return true if there are any elements in the sequence and false if there are no elements in the sequence. This method will not iterate the entire sequence (only maximum one element) since it will return true if it makes it past the first element and false if it does not.


1 Answers

Will IEnumerable enumerate every item and find the count (O(N)), or will it rely on List's Count property (O(1))?

It will use the Count property. Basically the implementation checks whether or not the object implements ICollection<T> or ICollection, and calls the relevant Count property if so. (The use of the non-generic ICollection was only introduced in .NET 4; in .NET 3.5 it only noticed ICollection<T>.)

It's only documented for ICollection<T>, however:

If the type of source implements ICollection<T>, that implementation is used to obtain the count of elements. Otherwise, this method determines the count.

like image 73
Jon Skeet Avatar answered Oct 07 '22 01:10

Jon Skeet