Kijana Woodard

Software Minimalism


IEnumerable Each()

Sunday, May 9, 2010

I’ve wanted to write an each statement for IEnumerable for a while, but haven’t bothered, mostly because other devs had decided to translate everything to List anyway so I just used .ForEach or a straight foreach as appropriate. A comment on my Avoiding FizzBuzz post by Matt Taylor spurred me to do an implementation.

Anyway, an Each() extension method on IEnumerable is trivial:

public static class IEnumerableExtensionMethods
{
    public static void Each<T>(
        this IEnumerable<T> list
      , Action<T> action)
    {
        foreach (var item in list)
            action(item);
    }
}


If you see a mistake in the post *or* you want to make a comment, please submit an edit.

You can also contact me and I'll post the comment.

1 Comments...
Landon Poch
Landon Poch • 12 years ago

You probably already know this but just for fun: https://blogs.msdn.com/b/ericli...

When using expressions they should be for evaluation, not for side effects. I found myself using SomeList.ForEach(x => { some action }) for a while. I stopped using it after reading that just as a way to build good functional programming habits. Even though { some action } isn't really an expression because it doesn't return anything, it just seems a little strange.