Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 9, 2013 17:58
Show Gist options
  • Save yetanotherchris/4746312 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4746312 to your computer and use it in GitHub Desktop.
Iterator design pattern example
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);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment