Tigraine

Daniel Hoelbling-Inzko talks about programming

IEnumerable<T>.Each as C# Extension Method

Posted by Daniel Hölbling on February 11, 2009

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<T> interface, since it would be a perfect place for quick inline method calls without having to write a full foreach statement.

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 :)

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more