All rules
CA1829Performance Enabled by default: As suggestion

Use Length/Count property instead of Enumerable.Count method

Use Length/Count property instead of Enumerable.Count method

Microsoft docs

Description

This rule flags the System.Linq.Enumerable.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 System.Linq.Enumerable.Count calls on the following collection types with Length property:

  • System.Array
  • System.Collections.Immutable.ImmutableArray`1

This rule flags System.Linq.Enumerable.Count calls on the following collection types with the Count property:

  • System.Collections.ICollection
  • System.Collections.Generic.ICollection`1
  • System.Collections.Generic.IReadOnlyCollection`1

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

Cause

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

How to fix violations

To fix a violation, replace the System.Linq.Enumerable.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: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (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

Example

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

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

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

When to suppress

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.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0