Iterator Pattern Example Code—Family Tree

See the following code for an example of the Iterator Pattern:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; class Person { public Person( ) {} public string Name {get; set;} public int Birth {get; set;} public Person (string name, int birth) { Name = name; Birth = birth; } public override string ToString ( ) { return ("["+Name+", "+Birth+"]"); } } class Node <T> { public Node ( ) {} public Node <T> Left{get; set;} public Node <T> Right {get; set;} public T Data {get; set;} public Node (T d, Node <T> left, Node <T> right) { Data = d; Left = left; Right = right; } } // T is the data type. The Node type is built-in. class Tree <T> { Node <T> root; public Tree( ) {} public Tree (Node <T> head) { root = head; } public IEnumerable <T> Preorder { get {return ScanPreorder (root);} } // Enumerator with Filter public IEnumerable <T> Where (Func <T, bool> filter) { foreach (T p in ScanPreorder(root)) if (filter(p)==true) yield return p; } // Enumerator with T as Person private IEnumerable <T> ScanPreorder (Node <T> root) { yield return root.Data; if (root.Left !=null) foreach (T p in ScanPreorder (root.Left)) yield return p; if (root.Right !=null) foreach (T p in ScanPreorder (root.Right)) yield return p; } } class IteratorPattern { // Iterator Pattern for a Tree Judith Bishop Sept 2007 // Shows two enumerators using links and recursion static void Main( ) { var family = new Tree <Person> (new Node <Person> ...

Get C# 3.0 Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.