Use Any() Instead of Count() To See if an IEnumerable Has Any Objects

An IEnumerable is an implementation that supports simple iteration using an enumerator. If you use LINQ you may see yourself using IEnumerables often. If you ever have one of these expressions and need to see if there is anything in it, be careful how you do your check. This quick tip will show you how you can use the Any() method instead of checking the full Count().

When working in C# and using LINQ you may find yourself often working with IEnumerable expressions. An important thing to note is that an IEnumerable is a thing that can be enumerated over, but you haven’t actually enumerated over it yet. As a result, you’ll see that there’s no Count property (like a generic list) or a Length property (like an array). Instead there’s a Count() method. The fact that its a method here indicates that it’s not merely access to a known piece of data, its an expensive call which will iterate over the collection to determine the count. If you ever have an IEnumerable and need to determine if there’s anything in it, you might write code like this:

[csharp]

IEnumerable<string> names = QueryForNames();

if(names.Count() > 0) {
// code here
}

[/csharp]

Since calling Count() will iterate over the entire collection, you can replace this with Any() which will try to iterate over the first object (if its exists). Any() will return true if there are any objects in the IEnumerable since it will return true if it makes it past the first object. The updated code using Any() looks like this:

[csharp]

IEnumerable<string> names = QueryForNames();

if(names.Any()) {
// code here
}

[/csharp]

Using Any() instead of Count() will slightly increase performance (more noticeably on larger collections) as it will only need to loop once if the collection contains anything.

Read more on the IEnumerable interface.

 

Mark Ursino

Mark is Sr. Director at Rightpoint and a Sitecore MVP.

 

8 thoughts on “Use Any() Instead of Count() To See if an IEnumerable Has Any Objects

  1. Nice tip. Performance is always an important consideration, especially with lists/ienumberables/arrays/etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.