Do not use CountAsync/LongCountAsync when AnyAsync can be used
Do not use CountAsync/LongCountAsync when AnyAsync can be used
Microsoft docsDescription
This rule flags the Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync and Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.LongCountAsync LINQ method calls used to check if the collection has at least one element. These method calls require enumerating the entire collection to compute the count. The same check is faster with the Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync method as it avoids enumerating the collection.
Cause
The Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync or Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.LongCountAsync method was used where the Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync method would be more efficient.
How to fix violations
To fix a violation, replace the Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync or Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.LongCountAsync method call with the Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync 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 CountAsync() or LongCountAsync() when AnyAsync() can be used from the list of options that's presented. !Code fix for CA1828 - Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used
Example
using System.Linq;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions;
class C
{
public async Task<string> M1Async(IQueryable<string> list)
=> await list.CountAsync() != 0 ? "Not empty" : "Empty";
public async Task<string> M2Async(IQueryable<string> list)
=> await list.LongCountAsync() > 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.