Skip to content

Files

Latest commit

 

History

History
31 lines (21 loc) · 792 Bytes

File metadata and controls

31 lines (21 loc) · 792 Bytes

Pattern: Use of Enumerable.Any() extension method

Issue: -

Description

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

Further Reading