Reputation: 9015
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
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:
Each
)Upvotes: 3
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