For(int i= , using extension´s

I’m a big fan of using ForEach and lambda instead of the regular kind of foreach;

// Old regular type
foreach(Bob bob in Bobs)

// Nicer extension lambda style
Bobs.ForEach(bob => Console.WriteLine(bob));

Not everyone agrees that the second version is clearer, but this is my blog, they can start their own blogs… 😉

But what about when you also need an index for the list, as I sometimes do? Then we’re stuck with the ancient “for(int i=” version, right? But no, Extensions to the rescue;

public static class Extensions
    public static void ForEachNumbered<T>(
        this IList<T> list, 
        Action<T, int> action)
        for (int i = 0; i < list.Count; i++)
            action(list[i], i);

Now I can write code link this instead (I’m not so convinced that anyone will ever find this clearer)

// Old regular type
for(int i=0;i<Bobs.Count;i++)
    Bob bob=Bobs[i];
    Console.WriteLine(string.Format("{0}: {1}", i, bob));

// Nicer extension lambda style
Bobs.ForEachNumbered((bob,i) => string.Format("{0}: {1}", i, bob));




About mfagerlund
Writes code in my sleep - and sometimes it even compiles!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: