CA1829: Use Length/Count property instead of Enumerable.Count method

Value
Rule ID CA1829
Category Performance
Fix is breaking or non-breaking Non-breaking

Cause

The Count LINQ method was used on a type that supports an equivalent, more efficient Length or Count property.

Rule description

This rule flags the Count LINQ method calls on collections of types that have equivalent, but more efficient Length or Count property to fetch the same data. Length or Count property does not enumerate the collection, hence is more efficient.

This rule flags Count calls on the following collection types with Length property:

This rule flags Count calls on the following collection types with the Count property:

The analyzed collection types may be extended in future to cover more cases.

How to fix violations

To fix a violation, replace the Count method call with use of the Length or Count property access. For example, the following two code snippets show a violation of the rule and how to fix it:

using System.Collections.Generic;
using System.Linq;

class C
{
    public int GetCount(int[] array)
        => array.Count();

    public int GetCount(ICollection<int> collection)
        => collection.Count();
}
using System.Collections.Generic;

class C
{
    public int GetCount(int[] array)
        => array.Length;

    public int GetCount(ICollection<int> collection)
        => collection.Count;
}

Tip

A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press Ctrl+. (period). Choose Use Length/Count property instead of Count() when available from the list of options that's presented.

Code fix for CA1829 - Use Length/Count property instead of Count() when available

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary collection enumeration to compute the count.

See also