Click here to Skip to main content
15,867,756 members
Articles / Programming Languages / C#

Iterator Pattern

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
19 Oct 2013CPOL2 min read 10.6K   7  
The iterator pattern’s role is to provide a way to access aggregate objects sequentially without the knowledge of the structure of the aggregate.

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Introduction

The iterator pattern’s role is to provide a way to access aggregate objects sequentially without the knowledge of the structure of the aggregate.
The pattern is widely used in C# and in .NET Framework. We have the IEnumerator and IEnumerable interfaces to help us to implement iterators for aggregates.
When you implement your own aggregate object, you should implement these interfaces to expose a way to traverse your aggregate.

Use Cases for the Iterator Pattern

You should use the pattern in the following cases:

  • You need a uniform interface to traverse different aggregate structures.
  • You have various ways to traverse an aggregate structure.  
  • You don't won't to expose the aggregate object's internal representation.

UML Diagram

Example in C# 

C#
#region Aggregate Item
class AggregateItem
{
    #region Properties
    /// <summary>
    /// The AggregateItem's data
    /// </summary>
    public string Data { get; set; }
    #endregion

    #region Ctor
    /// <summary>
    /// Construct a new AggregateItem with the given data
    /// </summary>
    /// <param name="data">The given data</param>
    public AggregateItem(string data)
    {
        Data = data;
    }
    #endregion
}
#endregion

#region Aggregate Object
interface Aggregate
{
    Iterator GetIterator();
}

class AggregateImpl : Aggregate
{
    #region Members
    private readonly List<AggregateItem> _aggregate;
    #endregion

    #region Properties
    /// <summary>
    /// The number of items in the aggregate
    /// </summary>
    public int Count
    {
        get
        {
            return _aggregate.Count;
        }
    }

    /// <summary>
    /// The indexer for the aggregate
    /// </summary>
    public AggregateItem this[int index]
    {
        get
        {
            return _aggregate[index];
        }
        set
        {
            _aggregate[index] = value;
        }
    }
    #endregion

    #region Ctor
    /// <summary>
    /// Construct a new AggregateImpl
    /// </summary>
    public AggregateImpl()
    {
        _aggregate = new List<AggregateItem>();
    }
    #endregion

    #region Aggregate Members
    /// <summary>
    /// Returns the Iterator for this aggregate object.
    /// </summary>
    /// <returns>Iterator</returns>
    public Iterator GetIterator()
    {
        return new IteratorImpl(this);
    }
    #endregion
}
#endregion

#region Iterator
interface Iterator
{
    object First();
    object Next();
    bool IsDone();
    object Current();
}

class IteratorImpl : Iterator
{
    #region Members
    private readonly AggregateImpl _aggregate;
    private int _nCurrentIndex;
    #endregion

    #region Iterator Members
    /// <summary>
    /// Return the first object of the iterator.
    /// </summary>
    /// <returns>First object of the iterator</returns>
    public object First()
    {
        return _aggregate[0];
    }

    /// <summary>
    /// Return the current object in the iterator and
    /// advance to the next one.
    /// </summary>
    /// <returns>The next object in the iterator</returns>
    public object Next()
    {
        object result = null;
        if (_nCurrentIndex < _aggregate.Count - 1)
        {
            result = _aggregate[_nCurrentIndex];

            _nCurrentIndex++;

        }

        return result;
    }

    /// <summary>
    /// Returns true if the iteration is done.
    /// </summary>
    /// <returns>True if the iteration is done</returns>
    public bool IsDone()
    {
        return _nCurrentIndex >= _aggregate.Count;
    }

    /// <summary>
    /// Return the current object in the iterator.
    /// </summary>
    /// <returns></returns>
    public object Current()
    {
        return _aggregate[_nCurrentIndex];
    }
    #endregion

    #region Ctor
    /// <summary>
    /// Construct a new IteratorImpl with the given aggregate.
    /// </summary>
    /// <param name="aggregate">The given aggregate</param>
    public IteratorImpl(AggregateImpl aggregate)
    {
        _nCurrentIndex = 0;
        _aggregate = aggregate;
    }
    #endregion
}
#endregion

There are 5 players in the example. The first player is an aggregate item which is a simple data structure.
We also have an aggregate interface which has a GetIterator method that returns the iterator. There is an Iterator interface that gives the guidelines of the iterator behavior. I used the two interfaces to implement an aggregate and an iterator.

The IEnumerator and IEnumerable Interfaces

The IEnumerator and the IEnumerable are the ways to implement the iterator pattern in C#.
The IEnumerable interface exposes the enumerator, which supports a simple iteration over a non-generic or generic collection. It is used in the collection itself to expose the functionality of enumerator. The IEnumerable is widely used in LINQ and it is the building block to expose LINQ functionality.
The IEnumerator interface supports a simple iteration over a non-generic or generic collection.
The enumerators are a read only way to traverse a collection. You should use these interfaces in order to implement the iterator pattern in C#. The way to implement them is close to the implementation that
I provided earlier for the iterator pattern. 

Simple Traverse Example 

Even though it is more preferable to use a foreach loop, you can traverse collections with the IEnumerator interface as shown in the following example:

C#
// build a new string list
var strList = new List<string>
                  {
                      "str1",
                      "str2",
                      "str3"
                  };

// get list enumerator
IEnumerator<string> enumerator = strList.GetEnumerator();

// use the enumerator to traverse the list
// and output the list's items to console
string str;

while (enumerator.MoveNext())
{
    str = enumerator.Current;

    if (!string.IsNullOrEmpty(str))
    {
        Console.WriteLine("{0}", str);
    }
}

Summary

To sum up, we are widely using the iterator pattern even if we don’t know it. Whenever you run a foreach loop, the iterator pattern is used underneath the hood.

The LINQ extensions are built upon the IEnumerable interface which is a part of the iterator pattern implementation in .NET Framework.

This article was originally posted at http://wiki.asp.net/page.aspx/496/iterator-pattern

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

755 members

Comments and Discussions

 
-- There are no messages in this forum --