Let's say I have a collection of expensive-to-generate objects stored in an IEnumerable:
IEnumerable<Expensive> expensiveObjects = CreateExpensiveIEnumerable();
Now I will iterate over everything in expensiveObjects
and afterwards, I want to know if it was empty.
Here is how I am doing that currently.
var count = 0;
foreach(var e in expensiveObjects)
{
count++;
//other processing
}
if (count == 0)
{
//do something
}
This works fine, but I'm asking here as a fishing expedition to figure out if there are any clever ways to implement this functionality without either:
- iterating over at least part of the collection twice by using the
Any()
method - Performing a
ToList()
up-front on my collection
Any other suggestions or should I just stick with a simple counting variable?
IEnumerable
but you also don't want to iterate it twice, which looks like the objects are generated each time. So which one is it? Could you describe the characteristics on theIEnumerable
in more detail? \$\endgroup\$ – svick Nov 15 '13 at 18:26yield return
statement, does that help? \$\endgroup\$ – Sven Grosen Nov 15 '13 at 18:30