Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Friday
Jan232009

C# Design Patterns: the Iterator pattern

Summary

Iterate through a list of items, with an enumerator class ordering the set/list before it is iterated through.

Example

Iterators are built into C# via foreach statements and IEnumerator. The iterator is the foreach statement, which requires the object it is iterating through to implement IEnumerator. The foreach statement calls GetEnumerator on the collection or class you specify. With the introduction of the yield keyword into C# this has been made even simpler.

namespace DesignPatterns
{
    private static void IteratorTest()
    {
        IteratorExample example = new IteratorExample();
        foreach (string item in example)
        {
            Console.WriteLine(item);
        }
    }

    public class IteratorExample : IEnumerable
    {
        Dictionary<string, string> _dictionary;

        public IteratorExample()
        {
            // Add 5 names to a key/value pair list.
            _dictionary = new Dictionary<string, string>();
            _dictionary.Add("Hans", "Pisces");
            _dictionary.Add("Fred", "Aquarius");
            _dictionary.Add("Andrew", "Gemini");
            _dictionary.Add("Zach", "Scorpio");
            _dictionary.Add("Berfa", "Cancer");
        }

        /// <summary>
        /// Demonstrates yield with IEnumerable.
        /// </summary>
        public IEnumerator GetEnumerator()
        {
            // Sort by name
            var sorted = from d in _dictionary orderby d.Key select d;

            // Iterate through the sorted collection
            foreach (KeyValuePair<string, string> item in sorted)
            {
                yield return item.Key;
                yield return string.Format("({0})",item.Value);
            }
        }
    }
}

The output is:

Andrew
(Gemini)
Berfa
(Cancer)
Fred
(Aquarius)
Hans
(Pisces)
Zach
(Scorpio)

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« C# Design patterns: the Strategy pattern | Main | C# MD5 and SHA encryption wrapper class »