Classes that implement System.Collection.ICollection, know how many elements they have in their sequence. They have a property Count which returns the number of sequence. Examples are List, Dictionary and Queue.
Other classes that implement IEnumerable might not implement ICollection. Thy don't have a property count. However you still can know the number of elements in the sequence by enumerating over all elements and counting them.
To me the latter method seems much slower.
The only thing that method Enumerable.Count(this IEnumerable) knows about the sequence is that it implements IEnumerable. It doesn't know that the sequence has a property that gives you the number of elements.
Normally this would mean that if you Count() a List, the function must iterate over all elements.
However, the implementation of Enumerable.Count(IEnumerable) could check if the sequence implements interface ICollection and if so it can return Count instead of enumerating over it.
Question: Is Enumerable.Count(this IEnumerable) smart enough to check if the sequence implements ICollection, or does it always iterate over all elements?
If the latter is the case, would it be smart to extend Enumerable with a Count function that checks if the object implements ICollection and if so return ICollection.Count()?
How about looking in the source code.
On line 1905 you can see the count method with the following lines:
ICollection<TSource> collectionoft = source as ICollection<TSource>;
if (collectionoft != null) return collectionoft.Count;
ICollection collection = source as ICollection;
if (collection != null) return collection.Count;
As you can see, the method uses the ICollection.Count
propertie, when the IEnumerable
is a ICollection
.
Take in account, the following method with the signature Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
does not implement this (because of the custom count method you provide ; ) )
EDIT:
It should also be mentioned, that the LongCount
methods do not use this property.
Because of all this, there is no need to implement your own Count()
.