IEnumerable.Each as C# Extension Method
February 11, 2009 by Daniel Hoelbling
A very long time ago I went through the Ruby in 20 minutes tutorial when I saw this:
@names.each do |name|
puts "Hallo, #{name}!"
end
When C# came out later I always wondered why there is no functional equivalent on the IEnumerable
At that time my knowledge of extension methods and delegates was too limited to do this myself, but that doesn’t mean it has to stay that way.
I finally remembered that I never got to it last time and implemented it today.
Oh and it’s so damn easy too:
public static class EachExtension
{
public static void Each<T>(this IEnumerable<T> enumberable, Action<T> action)
{
foreach (var item in enumberable)
{
action(item);
}
}
}
To use this .Each method now you simply need to be using the Namespace where the EachExtension is in and you can write code like this:
IEnumerable<string> x = new[] {"hello", "world", "how", "are", "you"};
x.Each(Console.WriteLine);
Or with multiple parameters:
IEnumerable<string> x = new[] {"hello", "world", "how", "are", "you"};
x.Each(p => Console.WriteLine("{0}", p));
Or, even whole inline method bodies:
IEnumerable<string> x = new[] {"hello", "world", "how", "are", "you"};
x.Each(p =>
{
Console.Write("Word:");
Console.WriteLine(p);
});
So, Lambdas are fun after all :)