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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow