Iterator Pattern Code Review

Define the Main Tree Object

Code Download

  • Download Description:iterator pattern download
  • .NET Framework:3.5
  • .NET Language:C#
  • Date Published:2009-07-01
  • Download Size:11 KB

Family Tree Structure

image showing family tree structure

Code Review

Code Walkthrough

Define the Tree class which contains the methods required to iterate through the family tree structure.

class Tree { Node m_root;
public Tree(Node head) { this.m_root = head; }
public IEnumerable<Person> Preorder { get { return this.ScanPreorder(this.m_root); } }
private IEnumerable<Person> ScanPreorder(Node root) { yield return(root.Data);
if (root.Child != null) { foreach (Person p in ScanPreorder(root.Child)) { yield return (p); } } if (root.Next != null) { foreach (Person p in ScanPreorder(root.Next)) { yield return (p); } } } public IEnumerable<Person> Where(Func<Person, Boolean> filter) { foreach (Person p in this.ScanPreorder(this.m_root)) { if (filter(p) == true) { yield return (p); } } } }

The ScanPreorder() method is the main method for transvering the tree and uses recursion to iterate from the root node to the left node and then to the right node for each node in the tree.

For the root node the method yields the data at that node, and for the left and right nodes, it yields a node to the enumerator. This node will act as the root node and the iteration will start again. In this way, the entire tree is transversed from left to right and top to bottom.

The Where() method acts as another enumerator, which also calls ScanPreorder() method but filters out the required Person objects according to the delegate supplied. The type of the delegate is Func <Person,bool>, meaning it takes a Person as a parameter on each iteration, and returns a boolean value.

The Tree class does not implement the IEnumerable<T> interface so in order to use LINQ functionality the Where() method was defined.