Executing a certain action for all elements in an Enumerable<T>

Daniel Magliola picture Daniel Magliola · Feb 9, 2009 · Viewed 45.3k times · Source

I have an Enumerable<T> and am looking for a method that allows me to execute an action for each element, kind of like Select but then for side-effects. Something like:

string[] Names = ...;
Names.each(s => Console.Writeline(s));

or

Names.each(s => GenHTMLOutput(s));   
// (where GenHTMLOutput cannot for some reason receive the enumerable itself as a parameter)

I did try Select(s=> { Console.WriteLine(s); return s; }), but it wasn't printing anything.

Answer

Jay Bazuzi picture Jay Bazuzi · Feb 9, 2009

A quick-and-easy way to get this is:

Names.ToList().ForEach(e => ...);