HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Check IEnumerable Count

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
countcheckienumerable

Problem

Let's say I have a collection of expensive-to-generate objects stored in an IEnumerable:

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.