For Loop with Count Question

beantownace

Active member
Joined
Feb 15, 2019
Messages
26
Programming Experience
5-10
Hello all,

Quick question and I should know this. If I have an IEnumerable and then below that a for loop if I need to set the last index to the Count of this IEnumerable should I get the count in a variable before the for loop where if I put like the code snippet below it would enumerate it each time the count?


ForLoop:
IEnumerable customers;

for(var i = 0; i < customers.Count(); i++)
{
}
 
You should always avoid enumerating a list multiple times if at all possible. You should always avoid executing the same complex code multiple times whatever it is. You should pretty much never call the same method or get the same property multiple times if you know that it will provide the same result every time anyway. In such cases, always get the desired result once at the start and store it for later use.

On a more specific point, it would be rare to use an IEnumerable like that anyway. The specific point is that they can be enumerated, so you'd normally use a foreach loop.
 
It depends on the class implementing the IEnumerable. The LINQ extension method tries to be smart and asked the the underlying implementation. If the underlying implementation is an array or list or some other type that knows its number of elements, then it will quickly return the count. On the other hand, if the implementation does not know its number of elements, the LINQ extension method will then enumerate all the items to count them.

So to answer your question, since you are talking to an interface and don't really know the underlying implementation, the safest course of action is to call Count() and store the value in a variable before starting your loop. The result will be enumerating the items twice: once when you call Count(), and the second time in your for loop.

In general, though, if all you intend to do is process each item in the collection, use foreach() so that you enumerate the items only once.
 
Back
Top Bottom