Iterators
Going through the documentation I found it hard to figure out how I could expose my custom Enumerator to foreach. I was trying to implement an “Inorder” traversal as a property to my Binary Search Tree, so that I could do the following.
BinarySearchTree<int> bst = new BinarySearchTree<int>();
bst.Add(150);
bst.Add(50);
bst.Add(175);
bst.Add(5);
bst.Add(55);
foreach (int i in bst.InOrder)
{
//Process elements here in Order.
}
Here is one to way to implement it. Implement a nested type InOrderCollection derived from IEnumerable<T> in your BinarySearchTree class.
public struct InOrderCollection : IEnumerable<T>
{
readonly BinarySearchTree<T> bst;
internal InOrderCollection(BinarySearchTree<T> pBst)
{
bst = pBst;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new InOrderEnumerator<T>(bst);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new InOrderEnumerator<T>(bst);
}
}
Now you can add the following property to your BinarySearchTree.
public IEnumerable<T> InOrder
{
get
{
return new InOrderCollection(this);
}
}
I realized this could be a generic sample in case you want to expose your collection’s Enumerators to foreach.
[This code snippet is provided under the Microsoft Permissive License.]