Greg
Greg

Reputation: 34838

c# hierarchy collection library? - anyone know of one (e.g. GetDirectChildren, GetAllChildren, GetParent)

Does anyone know of a solid C# library / approach to manage a hierarchy/web type collection?

This would be a library that would basic consist of the concept of nodes & relationships, for example to model web pages/files linked under a URL, or modeling IT infrastructure. It would have key methods such as:

So it's smarts would include the ability to "walk the tree" of nodes based on the relationships when someone does ask for "give me all the children under this node" for example.

It ideally include a persistence layer, to save/retrieve such data to/from a databases (e.g. with a Nodes and Relationships table).

EDIT 1

Upvotes: 3

Views: 2166

Answers (4)

Greg
Greg

Reputation: 34838

QuickGraph is the closest thing I've found so far...

http://quickgraph.codeplex.com/

Upvotes: 1

Ian Mercer
Ian Mercer

Reputation: 39307

There are various samples on the web for how to create a directed graph (which is what you are actually looking for). For example http://www.jrcalzada.com/post/2010/02/14/Generic-Graph-Class-in-C.aspx

Upvotes: 1

Ian Mercer
Ian Mercer

Reputation: 39307

The approach is easy, simply include a reference to an instance of self called 'Parent' and a collection of 'Children'. You can enforce this using the class constructor: require the Parent to be passed to the constructor and simply set Parent to that value and then add 'this' to the Children collection on the parent class.

e.g.

   public class Whatever
   {
      public Whatever Parent {get; private set;}
      protected List<Whatever> Children {get; private set;}


      public Whatever(Whatever parent)
      {
          this.parent = parent;
          this.Children = new List<Whatever>();
          if (parent != null)
          {
              parent.Children.Add(this);
          }
      }

      public IEnumerable<Whatever> AllChildren
      {
         return this.Children.Union(this.Children.SelectMany(child => child.AllChildren));
      }

With this in place AllChildren, DirectChildren, Root are all easily implemented.

When you serialize to a database you only need to record the ParentID for each instance and can rebuild the tree after loading them all. The node with no parent is the root.

Upvotes: 0

Related Questions