In later versions of .net, there is an extension method called Count()
associated with IEnumerable<T>
, which will use IList<T>.Count()
or ICollection.Count()
if the underlying enumerator supports either of those, or will iteratively count the items if it does not.
An important caveat not always considered with this: while an IEnumerable<DerivedType>
may generally be substituted for an IEnumerable<BaseType>
, a type which implements IList<DerivedType>
but does not implement ICollection
may be efficiently counted when used as an IEnumerable<DerivedType>
, but not when cast as IEnumerable<BaseType>
(even though the class would support an IList<DerivedType>.Count()
method which would return the correct result, the system wouldn't look for that--it would look for IList<BaseType>
instead, which would not be implemented.