LINQ Interview Question #73

What is the difference between Any and Count for existence checks?

Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate

Quick Interview Answer

Any expresses an existence check directly and can stop after finding the first matching element. Count calculates how many matching elements exist and may require more work.

Detailed Explanation

Any expresses an existence check directly and can stop after finding the first matching element. Count calculates how many matching elements exist and may require more work.

For database queries, Any is commonly translated to an existence-oriented SQL query, while Count asks the database for a count. Use Count when the actual number is required and Any when only existence matters.

Code Example

// Preferred for existence:
if (orders.Any(o => o.CustomerId == customerId))
{
    // At least one order exists.
}

// Use Count when the number itself is needed:
int orderCount = orders.Count(
    o => o.CustomerId == customerId);