These days, it is unusual to write an implementation of the Iterator pattern. Most of the modern languages included a library with a set of aggregate objects that follow this pattern as defined in the Gang of Four book.

In .Net, these objects are in the System.Collections namespace and they include classes such as Lists, Queues, Dictionaries, and also their specialised strongly typed (Generic) version.

The Gang Of Four defines two types of iterators: External and Internal. The External requires the client to traverse the items (by looping through the items until the end of the iterator). In contrast to this, the internal iterator delegates this process to a Traverse mix-in class that can be extended and customised.

I was looking for something similar to the internal iterator in .Net. That is, a generic way of passing an operation to a collection that would apply it to each of its items. None of the LinQ extension methods for collections seemed to do this, so I wrote one:

public static class Extensions
{
    public static void ApplyOperation<T>
                (this IEnumerable<T> iterator,
                Action<T> action)
    {
        foreach (var item in iterator)
            action(item);
    }
}

Which can be used as follows:

IEnumerable<string> cities =
            new string[] { "Dublin", "Buenos Aires", "Madrid" };
cities.ApplyOperation(x=>Console.WriteLine("City name: " + x));

or simply

new string[] {
    "Dublin",
    "Buenos Aires",
    "Madrid" }
    .ApplyOperation(
        x => Console.WriteLine("City name: " + x));

which prints the following output:

console