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?
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.
Any() is ALWAYS faster than . Count() > 0 ).
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.
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.
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.
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