LINQ  

Understanding Any() vs Count()

When working with collections in C#, two common ways to check whether data exists are:

collection.Any();
collection.Count() > 0;

They look similar, but they are not the same, especially in terms of performance..

Any() checks for existence

  • Returns as soon as it finds one element.

  • O(1) for most collections.

  • Does not require counting everything.

Count() Counts all elements

  • Must iterate the whole collection if it’s not a list.

  • O(n) for many enumerables.

  • Often unnecessary if you're only checking emptiness.

Why Any() Is Usually Faster

Consider

if (items.Any()) { ... }

As soon as the first element is found, the method stops.

But

if (items.Count() > 0) { ... }

It must often enumerate the entire collection, even if the first element already proves the list isn't empty.

BUT there Is an Exception: List<T>, array, etc.

For List<T>, T[], and other collections with a stored Count property:

myList.Count > 0

is O(1) and just reads an integer.

So for Lists and arrays, both are fast:

TypeAny()Count > 0
List<T>O(1)O(1)
ArrayO(1)O(1)

And that is because the underlying data structures store the count of elements as a separate field, rather than calculating it by iterating through the elements each time it's accessed.

But be careful, this is not the case when working with IEnumerable or SQL queries

IEnumerableO(1)O(n)
IQueryableSQL query → expensiveSQL query → more expensive