LINQ Any/All over Count

Use the Any or All methods instead of the Count method

Home DailyDrop

Daily Knowledge Drop

In most scenarios, the LINQ All or Any methods should be used instead of the Count method.

Count should be avoided, as it enumerates through every single entry in the collection to get the count, where Any/All will return as soon as the predicate condition is not met anymore.


Examples

All of the below examples, use the following collection:

var intList = Enumerable.Range(1, 10);

No predicate

When required to check if a list contains any items, the Any method should be used instead of Count:

// Bad
Console.WriteLine(intList.Count() > 0);
// Good
Console.WriteLine(intList.Any());

In this example, when Count is used, 10 items needs to be enumerated to get the full count, however Any will return true after one iteration, as soon as one item is found.
With only 10 items, the difference is negligible, however as the number of items in the collection increased, the difference will become more noticeable.


With predicate

The same logic applies when a predicate is supplied:

// Bad
Console.WriteLine(intList.Count(i => i > 5) > 0);
// Good
Console.WriteLine(intList.Any(i => i > 5));

// Bad
Console.WriteLine(intList.Count(i => i > 10) == 0);
// Good
Console.WriteLine(!intList.Any(i => i > 10));

The Count method will need to enumerable over all items in the collection, while Any will return true as soon as the first item which satisfies the predicate is reached.


All items

Similar logic applies when All items in the collection need to be checked:

// Bad
Console.WriteLine(intList.Count() == intList.Count(i => i  < 100));
// Good
Console.WriteLine(intList.All(i => i < 100));

Again, with Count, all items in the collection are enumerated over, while the All method will return false as soon as one item is reached which does not satisfy the predicate.


Notes

Generally, unless Count specifically needs to be used, Any or All should be preferred, especially as the number of items in the collection increases.


References

Using Count() instead of All or Any

Daily Drop 239: 20-01-2023

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net linq count any all