Question Iterating through a tree of objects


New member
Sep 2, 2015
Programming Experience
Hello all,

I have written a pretty simple tree data structure that implements the IEnumerable interface.

class Tree<T> : IEnumerable<T>

Everything is working great, I'm adding my nodes and the data is actually an object, so to create a node in my tree, I use something like this:

var tree = new Tree<QNode>();

After adding the top level tree, adding children to the tree is as simple as using tree.AddChild(root, QNode)

So now that I have my tree, if I want to iterate through them. If I use a simple Print method and iterate through the nodes:

public static void Print(this object self)

What I really want to do, is expose the methods and properties as I iterate through the node. For example, if I wanted to expose QNode.Name for each iteration, but I can't quite get the logic right in my head to do the implementation. Is it a change to the enumerate implementation? (private IEnumerable<T> enumerate(Node<T> root) or is it a change to the print method?

Thanks for your help, hopefully my question is clear enough!


Have you actually implemented IEnumerable<T> in your class? If so then it's a simple matter of using a foreach loop. If you have a Tree<QNode> then it's simply:
foreach (QNode node in myTree)
    // Use node here.
That said, I really don't think that a type implementing a tree structure should implement IEnumerable<T>. A tree is an inherently recursive structure so traversing it should be a recursive operation.
Hi jmcilhinney,

I have implemented the "private IEnumerable<T> enumerate(Node<T> root)" method, which iterates in the class. I have also done a quick print method to print out the list. The list stores the object as data in the class (public T Data).

The print looks like this:

public static void Print<T>(this IEnumerable<T> self)
            foreach (var item in self)

I thought maybe I just needed to replace var item with QNode item, but it doesnt expose all of the methods. I'm obviously not understanding something about list. Its just a simple list of QNodes.


In your Print method, the generic type parameter T is unconstrained, which basically means that it can be any type. As such, you can only access members that apply to any type within the method. If you were to override the ToString method of you QNode type then you should see the output of that from your Print method but you can't access members of the QNode type, or any type other than Object for that matter, inside the Print method.
Top Bottom