Similarly, you can check to see if any elements in the list meet a certain condition:
if (q.Any(i => i.IsSpecial))
If the query provider is something like LINQ to Entities, this will be translated into fairly efficient SQL using
For some reason, I see a lot of people write this code using the
Count() extension method instead (maybe they don't know about
Any()?), like this:
if (q.Count() > 0)
This is wrong for two reasons:
- It's imperative instead of expressive. Using
Any()tells the query provider, "Please determine if the list is non-empty using the most efficient way you can." Using
Count() > 0tells the query provider, "Please do exactly what I tell you, regardless of what I really need." Because LINQ is intended to support a variety of query providers, it is important to be expressive instead of imperative, and to let the provider specialize the implementation.
- Because we don't actually care about the exact count of items in the list, only that it is greater than zero, using the
Count()function can cause the provider to do considerably more work than necessary. Consider a linked list, or a SQL-based provider.