14

I want to store an organisation chart in a collection. I think a tree data structure will be best suited to my needs, as I need to add multiple nodes to one node.

LinkedList only provides adding one node to another node, if I understand it correctly.

I have looked at C5 treeset collection, but it doesn't seem to have Add() method to add more than 2 nodes to one node.

I have also looked at Treeview class from Windows Forms library, but I do not want to add Windows forms dll to my project, since I am building a service layer application. (or is it fine?)

I do not want to write my own tree collection class, if there is already one provided by 3rd party?

Any suggestion please?

Thanks

Otiel
  • 18,404
  • 16
  • 78
  • 126
gunnerz
  • 1,898
  • 5
  • 24
  • 39
  • Possible duplicate of http://stackoverflow.com/questions/66893/tree-data-structure-in-c-sharp ? – ikh Aug 08 '12 at 15:45
  • Thanks ikh I have seen that link, but I do not want to create my own collection. There must be someone out there who has created one dll and distributed it through Nuget! – gunnerz Aug 08 '12 at 15:47
  • 1
    The problem with pre-built tree-like collections is that there is no agreement on the generally accepted interface. Unlike lists, sets, or dictionaries, trees and graphs could have vastly different interfaces depending on who is implementing them, and for what purpose they need to utilize them. C# makes it rather easy to roll your own, and that is something I would definitely recommend doing in your situation. – Sergey Kalinichenko Aug 08 '12 at 15:50
  • 1
    Why not Write your own? a simple tree class takes about 10 minutes to write. – Marcelo De Zen Aug 08 '12 at 15:54

1 Answers1

34

Something like this can be a starting point. By using generics this one can hold a tree of anything

class TreeNode<T>
{
    List<TreeNode<T>> Children = new List<TreeNode<T>>();

    T Item {get;set;}

    public TreeNode (T item)
    {
        Item = item;
    }

    public TreeNode<T> AddChild(T item)
    {
        TreeNode<T> nodeItem = new TreeNode<T>(item);
        Children.Add(nodeItem);
        return nodeItem;
    }
}

A sample which holds a tree of strings

string root = "root";
TreeNode<string> myTreeRoot = new TreeNode<string>(root);
var first = myTreeRoot.AddChild("first child");
var second = myTreeRoot.AddChild("second child");
var grandChild = first.AddChild("first child's child");
Alberto
  • 23
  • 3
cellik
  • 2,116
  • 2
  • 19
  • 29