patterncsharpMinor
Check IEnumerable Count
Viewed 0 times
countcheckienumerable
Problem
Let's say I have a collection of expensive-to-generate objects stored in an IEnumerable:
Now I will iterate over everything in
Here is how I am doing that currently.
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:
Any other suggestions or should I just stick with a simple counting variable?
IEnumerable 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?
Solution
I think your approach is reasonable if you don't want (or can't) have the whole collection in memory. One minor change: if you don't need the count, just whether the collection was empty or not, use a simple
bool:bool any = false;
foreach(var e in expensiveObjects)
{
any = true;
//other processing
}
if (any)
{
//do something
}Code Snippets
bool any = false;
foreach(var e in expensiveObjects)
{
any = true;
//other processing
}
if (any)
{
//do something
}Context
StackExchange Code Review Q#35442, answer score: 5
Revisions (0)
No revisions yet.