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

Property Value
Rule ID CA1829
Title Use Length/Count property instead of Enumerable.Count method
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As suggestion

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 the 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.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA1829
// The code that's violating the rule is on this line.
#pragma warning restore CA1829

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA1829.severity = none

For more information, see How to suppress code analysis warnings.

See also