CA1827:當可以使用 Any() 時,請勿使用 Count()/LongCount()

屬性
規則識別碼 CA1827
標題 當可以使用 Any() 時,請勿使用 Count()/LongCount()
類別 效能
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

使用 Count() LongCount() 方法,其中 Any() 方法 會更有效率。

檔案描述

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

注意

此規則類似于 CA1860:避免使用 'Enumerable.Any()' 擴充方法 。 不過,該規則建議使用 Count 屬性,但此規則會套用至 Linq Count() 擴充方法

如何修正違規

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

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";
}
using System.Collections.Generic;
using System.Linq;

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

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

提示

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

Code fix for CA1827 - Do not use Count() or LongCount() when Any() can be used

隱藏警告的時機

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

隱藏警告

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

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

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

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

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

另請參閱