All rules
CA1827Performance Enabled by default: As suggestion

Do not use Count()/LongCount() when Any() can be used

Do not use Count()/LongCount() when Any() can be used

Microsoft docs

Description

This rule flags Count() and LongCount() LINQ method calls that are used to check if the collection has at least one element. These methods enumerate the entire collection to compute the count. The same check is faster with the Any() method as it avoids enumerating the collection. This rule is similar to CA1860: Avoid using 'Enumerable.Any()' extension method. However that rule suggests using the Count *property*, while this rule applies to the Linq Count() *extension method*.

Cause

The Count() or LongCount() *method* was used where the Any() method would be more efficient.

How to fix violations

To fix a violation, replace the System.Linq.Enumerable.Count or System.Linq.Enumerable.LongCount method call with the System.Linq.Enumerable.Any method. 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 Do not use Count() or LongCount() when Any() can be used from the list of options that's presented. !Code fix for CA1827 - Do not use Count() or LongCount() when Any() can be used

Example

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

class C
{
    public string M1(IEnumerable<string> list)
        => list.Count() != 0 ? "Not empty" : "Empty";

    public string M2(IEnumerable<string> list)
        => list.LongCount() > 0 ? "Not empty" : "Empty";
}

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