What does Any() mean in this LINQ query?

NoChance picture NoChance · May 27, 2012 · Viewed 7.5k times · Source

What is the Any() doing in the following query?

context.Customers
    .Include("InternetSales")
    .Where(c => c.InternetSales.Any())
    .Take(100);

How would you read out this query in plain English? For example, would the following be accurate?

"Get customers with their associated 100 internet sales."

(I know there is no "get" in the code, but you get what I mean.)

Answer

The Any operator checks whether some enumerable / collection contains at least one item, i.e. whether it is non-empty.

So I guess your query could read as:

"the first 100 customers that have made at least one internet sale"

or, somewhat closer to the metal:

"the first 100 Customer objects that have a non-empty InternetSales collection"

.Any() is similar to .Count() > 0, but it will consume at most one item in the collection, while Count consumes the complete collection, so Any is generally more efficient and works for infinite sequences, too. Provided you're not interested in the exact number of items, Any also expresses the intent of checking for non-emptiness more clearly.