Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use .Count() and .Count in the context of an IEnumerable<T>

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;
    }
}
like image 303
Richard Avatar asked May 18 '12 12:05

Richard


People also ask

How do you count in IEnumerable?

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.

What does count () do in C#?

Count() OverloadsReturns total number of elements in an array. Returns the total number of elements in an array that matches the specified condition using Func delegate. The following example displays the total number of elements in the array.

Which is better any or count C#?

Benchmark Comparison with 1000 Records Without the condition, both methods are pretty close, with the Any() method being slightly faster. On the other hand, we can see that the Any() method with the condition performs much better as it takes 2,734 ns, while the Count() method with the condition takes 5,505 ns.

Which is faster count or any?

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.


2 Answers

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 is ICollection<T> meaning that the length of the collection is known. Then the Count property is used but that is an implementation detail.

The best advice is to use the Count property if available for performance reasons.

Is .Count() predominately better saved for queryable collections that are yet to be executed, and therefore don't have an enumeration yet?

If your collection is IQueryable<T> and not IEnumerable<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 a Count property 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 computing Count() you might consider using .ToList() to pull the collection to the client side. It really depends on how you intend to use it.

like image 110
Martin Liversage Avatar answered Nov 02 '22 17:11

Martin Liversage


Count retrieves the property from a List (already calculated). Count() is an aggregation, like Sum(), Average(), etc. What it does is to count the items in the enumerable (I believe it internally uses the Count property if the enumerable is a list).

This is an example of the concrete use of the Count() method, when it doesn't just use the Count property:

var list = new List {1,2,3,4,5,6,7,8,9,10};

var count = list.Where(x => x > 5).Count();

Also, Count() has an overload that will count the items matching the predicate:

var count = list.Count(x => x > 5);
like image 38
Ivo Avatar answered Nov 02 '22 16:11

Ivo