Tar
Tar

Reputation: 9015

Possible multiple enumeration of IEnumerable when I merely return IEnumerable?

ReSharper says "Possible multiple enumeration of IEnumerable" on this code:

public static IEnumerable<T> Each<T>(this IEnumerable<T> @this, Action<T> action)
{
    foreach (var i in @this)
        action(i);

    return @this;
}

But I just return @this, I don't do anything else with it... is it warning me of possibility for additional enumeration once the function returns, or I'm missing something here ?

Upvotes: 0

Views: 281

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292455

But I just return @this, I don't do anything else with it...

Yes, but the caller will probably also enumerate it...

Anyway, using an iterator block like you did in your answer is better, because:

  • it avoids multiple enumeration
  • it maintains deferred execution (i.e. the source sequence won't be enumerated until you start enumerating the result of Each)

Upvotes: 3

Tar
Tar

Reputation: 9015

This avoids the warning and I assume that it's more efficient:

public static IEnumerable<T> Each<T>(this IEnumerable<T> @this, Action<T> action)
{
    foreach (var i in @this)
    {
        action(i);
        yield return i;
    }
}

Could someone verify that it is indeed more efficient (doesn't enumerate twice ?) ?

Upvotes: 1

Related Questions