IEnumerable<T>.Any() vs. IEnumerable<T>.Count() != 0

By Jay at May 10, 2008 11:10 Tags: , ,

This post is also available in french here. 

After reading this post from Eric Lippert, and reminding me that in the samples for this post, I'm using IEnumerable<T>.Count() where I'm actually not using the return value, therefore I'm enumerating through the whole collection for almost nothing.

I could have used IEnumerable<T>.Any(), which after looking at the IL code, just starts the enumeration, and stops just after one element if there is one and returns true, or if there isn't, returns false.

This is more effective, even without PLinq :)

blog comments powered by Disqus

About me

My name is Jerome Laban, I am a Software Architect, C# MVP and .NET enthustiast from Montréal, QC. You will find my blog on this site, where I'm adding my thoughts on current events, or the things I'm working on, such as the Remote Control for Windows Phone.