Author: Craig Stuntz
If you have a list, array, or query in a C#/LINQ application and need to check and see if the list is empty, the correct way to do this is to use the Any()
extension method:
if (q.Any())
{
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 EXISTS
.
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.” UsingCount() > 0
tells 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.