Improve your LINQ with .Any()

LINQ’s .Any() method is under-utilized, given the benefits it brings in making your code briefer, clearer, and more efficient. LINQ in general improves the expressiveness of your collection-manipulating code by using declarative statements instead of imperative foreach loops; .Any() is a great tool in that regard.

Here’s a representative example:

bool hasMissedDeadlines = deliverables
    .Where(d => d.Deadline < _systemClock.Today)
    .Count() > 0;

I want to determine if my to-do list has any items that are late, so I use .Where() to filter my list of deliverables down to items with a deadline in the past; then I take a .Count() of the resulting list, and see if that number is greater than zero. This is a plausible solution, and our years of SQL lead us to write LINQ this way. But it can be better.

Testing “count greater than zero” is a programmer’s way of saying “are there any?” So let’s just say any. As you might expect, .Any() returns a Boolean indicating whether the collection contains any items. Further, you can pass a lambda expression to specify the predicate “any like this.” (.Count() takes a predicate, too, by the way, but I really have seen “.Where().Count()” in use, so I wanted to start from there.)

Here’s the new version:

bool hasMissedDeadlines = deliverables
   .Any(d => d.Deadline < _systemClock.Today);

In addition to being shorter, this version more directly and declaratively states my intent: “Are there any late deliverables?”

This code also executes more efficiently. For .Count() to return a value, LINQ must iterate over all items in the collection, even though I don’t care how many items there are. .Any() will return as soon as it encounters an item that satisfies the predicate. It evaluates as few items as possible, giving me an efficient and readable solution.

About Sharon Cichelli

I am a Principal Technical Lead at Headspring, developing enterprise-changing software and coaching teams to deliver value without death marches. I am a .NET developer, open-source contributor, user group organizer, technical blogger, pinball fan, and Arduino enthusiast.
This entry was posted in refactoring and tagged . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • scichelli

    The above gives an alternative for the “if count > 0″ scenario. Keith Dahlby just tweeted a nice way of replacing “if count > 1.” He offers:


  • Ben Van Treese

    Also, a nice extension method is to just wrap this as a .None()
    so: bool None(this IEnumerable enumerable){ return !enumerable.Any(); }

    Makes life nice and code read like a sentence.

    • Sharon Cichelli

      (thumbsup)! :)