This site contains all my technical blog posts, and soon latest projects, code samples and articles.
Eventually it will also outline my career, experience and also detail how you can request me for freelance work.
Posted by Englestone | Filed under
I'm amazed (and ashamed) I've not come across this before.
It turns out when you have a variable of IEnumerable and you want to check it it’s not empty (number of items != 0), then using the .Any() method instead of .Count() > 0 is faster and what we should be doing.
This is because calling the .Count() iterates/enumerates through the collection calling .MoveNext() for each item in order to calculate the number of items (so if you have 1000 items I guess it calls that method 1000 times) ..
Whereas .Any() is returned as soon as it finds a valid item.
There are performance gains to be made here..
THE EXACT code that executes in the 2 extension methods (interesting)
Goodbye Count() > 0, hello .Any()