Implementing IEnumerable on a tree structure

krisg picture krisg · Dec 18, 2009 · Viewed 7.6k times · Source

Based on the work of these guys:

I am trying to implement a TreeView helper that would be used as such:

<%= Html.TreeView("records", 
                  Library.Instance.Records, 
                  r => r.Children, 
                  r => r.ID) %>

And the tree structure is defined like this:

public class Tree<T> : TreeNode<T> where T : TreeNode<T>
{ }


public class TreeNode<T> : IDisposable where T : TreeNode<T>
{
    public T Parent { get; set; }
    public TreeNodeList<T> Children { get; set; }
}


public class TreeNodeList<T> : List<TreeNode<T>> where T : TreeNode<T>
{
    public T Parent;

    public T Add(T node)
    {
        base.Add(node);
        node.Parent = (T)Parent;
        return node;
    }

    public void Remove(T node)
    {
        if (node != null)
            node.Parent = null;
        base.Remove(node);
    }
}

And the TreeView helper has this signature:

public static string TreeView<T>(this HtmlHelper htmlHelper, string treeId,
   IEnumerable<T> rootItems, Func<T, IEnumerable<T>> childrenProperty, 
   Func<T, string> itemContent, bool includeJavascript, string emptyContent)
{
    ...
}   

So as a result i need my Tree struture to implement IEnumerable so i can use it with the TreeView helper, and this leads to the question: where and how would i implement IEnumerable in this situation?

Answer

Eric Lippert picture Eric Lippert · Dec 18, 2009

This article by Wes Dyer is good reading for anyone who wants to implement a recursive tree iterator:

https://docs.microsoft.com/en-us/archive/blogs/wesdyer/all-about-iterators