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.
Rule description
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.
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:
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";
}using System.Linq;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions;
class C
{
public async Task<string> M1Async(IQueryable<string> list)
=> await list.AnyAsync() ? "Not empty" : "Empty";
public async Task<string> M2Async(IQueryable<string> list)
=> await list.AnyAsync() ? "Not empty" : "Empty";
}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 CA1828
// The code that's violating the rule is on this line.
#pragma warning restore CA1828To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1828.severity = noneFor more information, see How to suppress code analysis warnings.
Related rules
- CA1826: Use property instead of Linq Enumerable method
- CA1827: Do not use Count/LongCount when Any can be used
- CA1829: Use Length/Count property instead of Enumerable.Count method