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>();
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;
return new InOrderEnumerator<T>(bst);
Now you can add the following property to your BinarySearchTree.
public IEnumerable<T> InOrder
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.]