You could use the (chainable, but lazily evaluated) Select
, first doing your operation, and then returning identity (or something else if you prefer)
IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });
You will need to make sure it is still evaluated, either with Count()
(the cheapest operation to enumerate afaik) or another operation you needed anyway.
I would love to see it brought in to the standard library though:
static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
return src.Select(i => { action(i); return i; } );
}
The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p))
which is effectively equivalent to foreach, but lazy and chainable.
Parallel.ForEach
forEnumerable.ForEach
only to rediscover the latter doesn't exist. C# missed a trick to make things easy here. – Colonel Panic