views:

86

answers:

3

In the app I am writing, I am trying to find a way to store hierarchies effectively. Here is an example.

At the bottom, you can see the nodes to be stored. Should I use multi dimensional lists? That doesn't seem very optimal, right? I was thinking holding references like so:

node.Parent
node.Children { collection }

Anyone has experience with this kind of stuff?

+1  A: 

Yeah. You have the right idea. If you need a two-directional hierarchy, I wouldn't use a multi-dimensional list... I would add a node to the tree and each node contains a parent and a collection of children.

You are on the right track.

Brian Genisio
+1  A: 

This is a fairly basic implementation of a tree, yes. If choose to make your collection for the children an IList or IEnumable or ArrayList, etc is up to you.

I would strongly suggest you build a generic implementation instead of one typed to your domain model, however that is up to you.

Chad Ruppert
Thanks, in your second paragraph, you mean writing a generic CustomCollection<T>?
Joan Venge
No, more Like Treenode<T> which contains TreeNode<T> Parent and IEnumerable<Treenode<T>> Children
Chad Ruppert
Note that it only applies, as Lucero mentions in a post below, if all objects are of the same type or abstraction thereof.
Chad Ruppert
Thanks, so like Node : BaseNode, Node Parent, IEnumerable<Node> Children ? If I do that, would the Parent/Children cast the actual class down?
Joan Venge
Have two generic type parameters, one for branches, one for leaves.
Pete Kirkham
That's very good advice. I tend to use trees where leaves can be branches, but that's entirely up to you.
Chad Ruppert
If you use generics, you will have to have a non-generic base class (or an interface) which you also use as constraint.
Lucero
+1  A: 

If not all items are of the same type, I may use an abstract base class for a linked list and children collections in such a situation.

Lucero
Thanks, so like Node : BaseNode, Node Parent, IEnumerable<Node> Children ? If I do that, would the Parent/Children cast the actual class down?
Joan Venge
We,, I guess the children can be of different types. However, using generics, you could in fact have a strongly typed parent if necessary. But usually you just use the base class in this pattern.
Lucero