LP on .NET

October 27, 2010

Executing an Action on a Collection

Filed under: .NET,C#,Software Development — Larry Parker @ 9:53 am

When I need to iterate through a collection of items (e.g. an array or a list) I typically use the “foreach” keyword like this:

String[] citiesArray = { "New York", "Boston", "Chicago" };

foreach (String city in citiesArray)
    BookFlight(city);

This is a very straightforward and acceptable approach.

However, I often find myself thinking in a more functional way and would simply like to execute some action on each item in a collection.

We can actually do this on lists.  Continuing with the above example:

List<String> citiesList = citiesArray.ToList();

citiesList.ForEach(o => BookFlight(o));

The ForEach method is part of the List<T> class and executes an Action<T> delegate on each element in the list.

This is a nice succinct way to do it, but C# unfortunately does not let us do this out of the box on arrays.

A simple workaround is to write our own ForEach extension method for IEnumerable<T> (which arrays implement).  Here’s the code:

public static class EnumerableExtensions
{
    public static void ForEeach<T>(this IEnumerable<T> collection, Action<T> action)
    {
        foreach (T element in collection)
            action(element);
    }
}

Now we can call the ForEach method on our array, just like we did on our list:

citiesArray.ForEeach(o => BookFlight(o));

Since our extension method is for IEnumerable<T>, we can use it on any collection that implements IEnumerable<T>.  This includes dictionaries and most results from LINQ operators.

I would not recommend using this approach on anything that requires more than a simple call on each element.  Being succinct is nice, but sometimes it can decrease code readability and make debugging a bit harder.

But for a simple call on each element in a collection (like BookFlight in the example above), the ForEach extension method can be very handy.

Advertisements

2 Comments »

  1. One can try citiesArray.ToList() and then use it as a List

    Comment by Not specified — September 21, 2011 @ 4:38 am | Reply

  2. One thing you can’t do with .ForEach is break out of the loop.

    Comment by Jamie Burks — September 29, 2011 @ 5:17 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Create a free website or blog at WordPress.com.

%d bloggers like this: