skip to content

In C# LINQ, why is Any() preferred over Count() > 0 for an existence check, and when does the choice make no difference?

level: middleimportance: should knowfreq 60%

answer

  1. stop at the first element
  2. ICollection<T> shortcut
  3. filtered sequences have no cheap count
  4. CA1827 and CA1860

basics

~20 s

Any() stops at the first element, while Count() on a filtered or lazy sequence walks every element to finish counting. On a List<T> or array, Count() reads the Count property, so both are cheap and the property itself is clearest.

solid answer

~40 s

`Enumerable.Count()` first checks whether the source implements `ICollection<T>` (or is one of LINQ's own iterators that knows its size) and returns that count without enumerating. Otherwise, for example over `staff.Where(e => e.Salary > 4000m)`, it runs the predicate on every element. `Any()` asks for one element and stops, so on 10,000 salaries where the first match is at position 1,001 it runs the predicate 1,001 times against 10,000 for `Count() > 0`. On a `List<T>` or an array there is no cost difference; there the clearest code is the `Count` or `Length` property, which is what analyzer rules CA1829 and CA1860 suggest, while CA1827 flags `Count()` used as an existence test. `Any(predicate)` and `Where(predicate).Any()` do the same work.

code

csharp · 22 lines
csharp
using System;
using System.Collections.Generic;
using System.Linq;

var salaries = Enumerable.Range(1, 10_000).Select(i => 3_000m + i).ToList();
int checks = 0;
IEnumerable<decimal> highPaid = salaries.Where(s => { checks++; return s > 4_000m; });

checks = 0;
bool viaCount = highPaid.Count() > 0;
Console.WriteLine($"Count() > 0 : {viaCount}, predicate calls = {checks}");  // 10000

checks = 0;
bool viaAny = highPaid.Any();
Console.WriteLine($"Any()       : {viaAny}, predicate calls = {checks}");    // 1001

checks = 0;
bool direct = salaries.Any(s => { checks++; return s > 4_000m; });
Console.WriteLine($"Any(pred)   : {direct}, predicate calls = {checks}");    // 1001

Console.WriteLine(salaries.Count);                                // property, no enumeration
Console.WriteLine(highPaid.TryGetNonEnumeratedCount(out int n)); // False: a filter has no cheap count

go deeper

for a junior

Use Any() to ask whether a query has results and the Count or Length property on lists and arrays. Remember that Count() > 0 asks a bigger question than needed.

for a middle

Explain the ICollection<T> shortcut in Count(), why a filtered query has no cheap count, and how Any() stops after one element.

for a senior

Spot hidden full scans and double enumeration in review, use TryGetNonEnumeratedCount for pre-sizing, and enable CA1827, CA1829 and CA1860 instead of relying on reviewers.

for a principal

Decide which LINQ performance rules the team enforces as analyzer errors versus suggestions, weighing noise against the cost of scans on hot paths.

## Two questions that look alike "Is there at least one?" and "How many are there?" have different costs. `Enumerable.Any()` answers the first; `Enumerable.Count()` answers the second. Writing `Count() > 0` asks the expensive question and throws most of the answer away. ## What each method does in the runtime `Count()` in `System.Linq` takes a series of shortcuts before it enumerates: 1. if the source implements `ICollection<T>` (a `List<T>`, an array, a `HashSet<T>`), it returns `collection.Count`; 2. if the source is one of LINQ's own iterators that can compute its size, such as a `Select` over a list, it asks that iterator; 3. if it implements the non-generic `ICollection`, it returns that `Count`; 4. otherwise it enumerates every element and counts them. `Any()` takes similar shortcuts when a count is cheap, and otherwise calls `MoveNext()` **once**. `Any(predicate)` tests elements until the first one passes. ## Where the difference is real The cost gap appears when the source has no cheap count: - a filtered query such as `staff.Where(e => e.Salary > 4000m)`; - a `yield return` iterator or any lazy pipeline; - a sequence whose elements are expensive to produce, such as lines read from a file. | Source | `Count() > 0` | `Any()` | |---|---|---| | `List<Employee>` | reads `Count`, O(1) | reads `Count`, O(1) | | `employee[]` | reads `Length` through `ICollection<T>`, O(1) | O(1) | | `list.Where(pred)`, first match at position k of n | runs `pred` n times | runs `pred` k times | | an infinite generator | counts until `int` overflows, then throws `OverflowException` | returns at the first element | The last row is not academic: on a pipeline built over an endless sequence `Count()` never produces a useful answer, while `Any()` returns at once. ## Where it makes no difference On a materialised collection both calls are constant time. The advice then shifts from performance to clarity: use the property. The .NET code-analysis rules encode this: - **CA1827** flags `Count()` or `LongCount()` used only to test for at least one element and suggests `Any()`; - **CA1829** flags `Enumerable.Count()` on a type that has a `Length` or `Count` property; - **CA1860** flags `Enumerable.Any()` on a type that has a `Length`, `Count` or `IsEmpty` property. So on a `List<T>` neither `Any()` nor `Count() > 0` is preferred: `list.Count > 0` is. Severity and enabling these rules are covered with warnings and analyzers. ## Related operators - `Count(predicate)` always tests every element, even on a `List<T>`, because the property cannot answer a filtered question. - `TryGetNonEnumeratedCount(out int count)` returns `true` with the count only when it is cheap, and `false` for a filtered query, which lets code pre-size a buffer without forcing an enumeration. - `All(predicate)` is the mirror of `Any`: it stops at the first element that fails. - `List<T>.Exists(Predicate<T>)` answers the same question as `Any(predicate)` on a list without going through LINQ; both stop at the first match. ## The trap after the check Calling `Any()` on a lazy query and then looping over the same query runs the pipeline twice, once partially and once fully; how deferred queries re-run is the subject of deferred execution. If the next step needs the elements, materialise once with `ToList()` and test `list.Count`. ## In review - Replace `Count() > 0` on a query with `Any()`. - Replace `Any()` or `Count()` on a `List<T>` or array with the property. - Prefer `Any(predicate)` to `Count(predicate) > 0`; the first stops early, the second cannot.

  • Does Count(predicate) on a List<T> use the list's Count property?
    No. The property answers only "how many elements in total". `Count(predicate)` must test every element to know how many pass, so it always walks the whole list. That is why `Count(e => e.Salary > 4000m) > 0` is slower than `Any(e => e.Salary > 4000m)`, which stops at the first passing element.
  • To split 1,000 employees into pages of 50 for an export, why reach for Chunk rather than Count with Skip and Take?
    `Chunk(50)` walks the sequence once and yields `Employee[]` pages of 50, with a shorter last page when the total is not a multiple of 50. Computing `Count()` and then calling `Skip(i * 50).Take(50)` per page re-enumerates a lazy source once per page. A size below 1 makes `Chunk` throw `ArgumentOutOfRangeException`.

  • Count() always enumerates the whole collection, even a List<T>
  • Any() and Count() > 0 cost the same on a filtered query
  • Count(predicate) on a List<T> reads the Count property
  • On a List<T>, Any() is clearer than checking the Count property
  • Calling Any() before a foreach on a lazy query is free