C# Interview Question #46

What is the difference between Any() and Count() in LINQ?

LINQ & Querying Mid-Level Intermediate

Quick Interview Answer

Any checks whether at least one element exists or satisfies a condition. Count calculates the number of matching elements.

Detailed Explanation

Any checks whether at least one element exists or satisfies a condition. Count calculates the number of matching elements.

When only existence is required, Any is generally preferable because a provider or collection may stop after finding the first match. In EF Core, Any commonly translates to an efficient SQL EXISTS query.

Count should be used when the actual number of records is needed.

Code Example

bool hasProducts = products.Any();

bool hasActive = products.Any(p => p.IsActive);

int activeCount = products.Count(p => p.IsActive);