Avoid using 'Enumerable.Any()' extension method
Avoid using 'Enumerable.Any()' extension method
Microsoft docsDescription
To determine whether a collection type has any elements, it's more efficient and clearer to use the Length, Count, or IsEmpty (if possible) properties than to call the System.Linq.Enumerable.Any method.
Any(), which is an extension method, uses language integrated query (LINQ). It's more efficient to rely on the collection's own properties, and it also clarifies intent. This rule is similar to CA1827: Do not use Count()/LongCount() when Any() can be used. However, that rule applies to the Linq Count() *method*, while this rule suggests using the Count *property*.
Cause
System.Linq.Enumerable.Any is called on a type that has a Length, Count, or IsEmpty *property*.
How to fix violations
Replace a call to Any() with a call to the collection's Length, Count, or IsEmpty property.
Example
bool HasElements(string[] strings)
{
return strings.Any();
}
bool HasElements(string[] strings)
{
return strings.Length > 0;
}When to suppress
It's safe to suppress this warning if performance isn't a concern.