Pattern: Use of Enumerable.Any()
extension method
Issue: -
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 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.
Example of incorrect code:
bool HasElements(string[] strings)
{
return strings.Any();
}
Example of correct code:
bool HasElements(string[] strings)
{
return strings.Length > 0;
}