What does Any () mean in this LINQ query?
What does Any()
in the following query?
context.Customers .Include("InternetSales") .Where(c => c.InternetSales.Any()) .Take(100);
How would you read this query in plain English? For example, can one be exact?
"Get customers with 100 online sales."
(I know that there is no “get” in the code, but you understand what I mean.)
The Any
operator checks if any enumerable / collective contains at least one element, i.e. whether he is nonempty.
So, I assume that your request could be read as:
"The first 100 customers to complete at least one online sale"
or, slightly closer to the metal:
"The first 100
Customer
sites that contain a non-empty collection ofInternetSales
.Any()
is similar to .Count() > 0
, but it will consume no more than one element in the collection, and Count
consumes the full collection, so Any
is usually more efficient and works for infinite sequences. If you are not interested in the exact number of elements, Any
also expresses an intention to more clearly verify non-emptyness.