Count vs. Any : Enumerating
Count vs. Any : Enumerating
com/enumeration-in-net-d5674921512e
Enumerating
The simplest way to enumerate is to use a foreach loop. Lets start
with a simple method that takes an IEnumerable<int> and outputs
all its items to the console:
You can check at SharpLab that, in reality, the above code is
expanded to awhile loop. Focusing on the enumeration, we can
resume it to this:
Notice that, first a new instance of an IEnumerator is created. Next,
it starts a while loop calling MoveNext(), stopping when false is
returned. When it’s true, the Current property returns the new
value.
The generic version of IEnumerable implements IDisposable so
the usingkeyword is used to take care of that.
{
var count = 0;
while (enumerator.MoveNext())
count++;
return count;
if (!enumerable.Any())
return;
// do something here
}
Usually, you don’t even need to check if it’s empty. The foreach doesn’t enter the loop in that case.
Here’s an implementation of Average() that creates one single instance of IEnumerator and
enumerates the collection only once: