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:

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:

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.

Continuous Integration: Early indicators mean inexpensive fixes