Pattern: Missing use of Any()
Issue: -
This rule flags Count()
and LongCount()
LINQ method calls that are used to check if the collection has at least one element. These methods enumerate the entire collection to compute the count. The same check is faster with the Any()
method as it avoids enumerating the collection.
Example of incorrect code:
class Test
{
public string M1(IEnumerable<string> list)
=> list.Count() != 0 ? "Not empty" : "Empty";
public string M2(IEnumerable<string> list)
=> list.LongCount() > 0 ? "Not empty" : "Empty";
}
Example of correct code:
class Test
{
public string M1(IEnumerable<string> list)
=> list.Any() ? "Not empty" : "Empty";
public string M2(IEnumerable<string> list)
=> list.Any() ? "Not empty" : "Empty";
}