CA1827:如果可以使用 Any(),请勿使用 Count()/LongCount()

属性
规则 ID CA1827
标题 如果可以使用 Any(),请勿使用 Count()/LongCount()
类别 “性能”
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用 作为建议

原因

在使用 Any() 方法会更有效的情况下使用了 Count()LongCount() 方法

规则说明

此规则将标记 Count()LongCount() LINQ 方法调用,用于检查集合是否有至少一个元素。 这些方法会枚举整个集合来计算计数。 使用 Any() 方法进行相同检查的速度会更快,因为它可以避免枚举集合。

注意

此规则类似于 CA1860:避免使用“Enumerable.Any()”扩展方法。 但是,该规则建议使用Count属性,而此规则适用于 Linq Count()扩展方法

如何解决冲突

若要解决冲突,请将 CountLongCount 方法调用替换为 Any 方法。 例如,以下两个代码片段显示了规则冲突及其解决方法:

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+.(句点)”。 从提供的选项列表中,选择“如果可以使用 Any(),请勿使用 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

有关详细信息,请参阅如何禁止显示代码分析警告

另请参阅