An IEnumerable
is an implementation that supports simple iteration using an enumerator. If you use LINQ you may see yourself using IEnumerable
s 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.
Good call. just used this today.
Funny, I did this all the time without thinking twice but after reading this I’ve switched completely. Excellent point.
Good point. Optimized code
Good Info
Thanks for the tips. Never think about that.
Nice tip. Performance is always an important consideration, especially with lists/ienumberables/arrays/etc.