共用方式為


CA1828:不要在可使用 AnyAsync 時使用 CountAsync/LongCountAsync

屬性
規則識別碼 CA1828
標題 不要在可使用 AnyAsync 時使用 CountAsync/LongCountAsync
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

CountAsync使用 或 LongCountAsync 方法時, AnyAsync 方法會更有效率。

檔案描述

此規則會 CountAsync 標幟 用來檢查集合是否至少有一個專案的 和 LongCountAsync LINQ 方法呼叫。 這些方法呼叫需要列舉整個集合來計算計數。 方法的相同檢查速度較快 AnyAsync ,因為它可避免列舉集合。

如何修正違規

若要修正違規,請將 或 LongCountAsync 方法呼叫取代 CountAsyncAnyAsync 方法。 例如,下列兩個程式碼片段會顯示違反規則,以及如何修正它:

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";
}

提示

Visual Studio 中有一個程式碼修正程式碼可供此規則使用。 若要使用它,請將游標放在違規上,然後按 Ctrl + 。 (句號)。 當 AnyAsync() 可從所呈現的選項清單中使用 AnyAsync() 時,請選擇 [請勿使用 CountAsync()] 或 [LongCountAsync(]。

Code fix for CA1828 - Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used

隱藏警告的時機

如果您不擔心不必要集合列舉對計算計數的效能影響,則隱藏此規則的違規是安全的。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA1828
// The code that's violating the rule is on this line.
#pragma warning restore CA1828

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA1828.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

另請參閱