Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to check the Count() of an Enumerable before foreach

Tags:

c#

Is there any speed improvement or indeed point in checking the Count() of an Enumerable before iterating/foreaching over the collection?

List<int> numbers = new List<int>();

if(numbers.Count() > 0)
{
    foreach(var i in numbers) {/*Do something*/}
}
like image 771
Coops Avatar asked Jan 08 '14 08:01

Coops


2 Answers

No, the opposite can be true. If it's not a collection (like a List or Array) but a deferred executed query it must be executed completely which can be very expensive, just to determine the count. In your example it's actually a List, Enumerable.Count is clever enough to try to cast it to a ICollection<T>/ICollection first . If that succeeds the Count property is used.

So just use the foreach. It doesn't hurt if the sequence is empty, the loop will be exited immediately.

For the same reason it's better to use Enumerable.Any instead of Count() > 0 if you just want to check if a sequence contains at least one element. The intention is also more clear.

like image 73
Tim Schmelter Avatar answered Sep 21 '22 18:09

Tim Schmelter


If your Enumarable is lazy evaluated (LINQ) the call to Count() is actually very bad since it evaluates the whole Enumerable.

Since foreach doesn't execute if the Enumarable is empty it's best to not use Count.

like image 25
Martin Walter Avatar answered Sep 21 '22 18:09

Martin Walter