Skip to content

Latest commit

 

History

History
45 lines (32 loc) · 1.33 KB

File metadata and controls

45 lines (32 loc) · 1.33 KB

Pattern: Missing use of AnyAsync()

Issue: -

Description

This rule flags the CountAsync and 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 AnyAsync method as it avoids enumerating the collection.

Example of incorrect code:

using System.Linq;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions;

class Test
{
    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";
}

Example of correct code:

using System.Linq;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions;

class Test
{
    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";
}

Further Reading