I’m aware that .Count() is an extension method in LINQ, and that fundamentally it uses the .Count, so I’m wondering, when should I use Count() and when should I use .Count? Is .Count() predominately better saved for queryable collections that are yet to be executed, and therefore don’t have an enumeration yet? Am I safer simply always using .Count() extension method, or vice versa for the property? Or is this solely conditional depending on the collection?
Any advice, or articles, are greatly appreciated.
Update 1
After decompiling the .Count() extension method in LINQ it appears to be using the .Count property if the IEnumerable<T> is an ICollection<T> or ICollection, which is what most answers have suggested. The only real overhead now that I can see is the additional null and type checks, which isn’t huge I suppose, but could still make a small amount of difference if performance were of the utmost importance.
Here’s the decompiled LINQ .Count() extension method in .NET 4.0.
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
ICollection collection2 = source as ICollection;
if (collection2 != null)
{
return collection2.Count;
}
int num = 0;
checked
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
}
The extension method works on any
IEnumerable<T>but it is costly because it counts the sequence by iterating it. There is an optimization if the sequence isICollection<T>meaning that the length of the collection is known. Then theCountproperty is used but that is an implementation detail.The best advice is to use the
Countproperty if available for performance reasons.If your collection is
IQueryable<T>and notIEnumerable<T>then the query provider may be able to return the count in some efficient maner. In that case you will not suffer a performance penalty but it depends on the query provider.An
IQueryable<T>will not have aCountproperty so there is no choice between using the extension method and the property. However, if you query provider does not provide an efficient way of computingCount()you might consider using.ToList()to pull the collection to the client side. It really depends on how you intend to use it.