<p>I was looking for a tree or graph data structure in C#, but I guess there isn't one provided. <a href="http://msdn.microsoft.com/en-us/library/ms379574.aspx" rel="noreferrer">An Extensive Examination of Data Structures Using C# 2.0</a> a bit about why.  Is there a convenient library which is commonly used to provide this functionality?  Perhaps through a <a href="https://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">strategy pattern</a> to solve the issues presented in the article.</p>
<p>I feel a bit silly implementing my own tree, just as I would implementing my own ArrayList.</p>
<p>I just want a generic tree which can be unbalanced.  Think of a directory tree.  <a href="https://itu.dk/research/c5/" rel="noreferrer">C5</a> looks nifty, but their tree structures seem to be implemented as balanced red-black trees better suited to search than representing a hierarchy of nodes.</p>

[{'answer_id': 66933, 'author': 'McKenzieG1', 'author_id': 3776, 'author_profile': 'https://Stackoverflow.com/users/3776', 'pm_score': 5, 'selected': False, 'text': '<p>The generally excellent <a href="http://www.itu.dk/research/c5/" rel="noreferrer">C5 Generic Collection Library</a> has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven\'t used any of the tree structures specifically.)</p>\n'}, {'answer_id': 66956, 'author': 'David Boike', 'author_id': 10039, 'author_profile': 'https://Stackoverflow.com/users/10039', 'pm_score': 8, 'selected': True, 'text': "<p>My best advice would be that there is no standard tree data structure because there are so many ways you could implement it that it would be impossible to cover all bases with one solution.  The more specific a solution, the less likely it is applicable to any given problem.  I even get annoyed with LinkedList - what if I want a circular linked list?</p>\n\n<p>The basic structure you'll need to implement will be a collection of nodes, and here are some options to get you started.  Let's assume that the class Node is the base class of the entire solution.</p>\n\n<p>If you need to only navigate down the tree, then a Node class needs a List of children.</p>\n\n<p>If you need to navigate up the tree, then the Node class needs a link to its parent node.</p>\n\n<p>Build an AddChild method that takes care of all the minutia of these two points and any other business logic that must be implemented (child limits, sorting the children, etc.)</p>\n"}, {'answer_id': 2012855, 'author': 'Aaron Gage', 'author_id': 226861, 'author_profile': 'https://Stackoverflow.com/users/226861', 'pm_score': 7, 'selected': False, 'text': '<pre><code>delegate void TreeVisitor&lt;T&gt;(T nodeData);\n\nclass NTree&lt;T&gt;\n{\n    private T data;\n    private LinkedList&lt;NTree&lt;T&gt;&gt; children;\n\n    public NTree(T data)\n    {\n         this.data = data;\n        children = new LinkedList&lt;NTree&lt;T&gt;&gt;();\n    }\n\n    public void AddChild(T data)\n    {\n        children.AddFirst(new NTree&lt;T&gt;(data));\n    }\n\n    public NTree&lt;T&gt; GetChild(int i)\n    {\n        foreach (NTree&lt;T&gt; n in children)\n            if (--i == 0)\n                return n;\n        return null;\n    }\n\n    public void Traverse(NTree&lt;T&gt; node, TreeVisitor&lt;T&gt; visitor)\n    {\n        visitor(node.data);\n        foreach (NTree&lt;T&gt; kid in node.children)\n            Traverse(kid, visitor);\n    }\n}\n</code></pre>\n\n<p>Simple recursive implementation...\n&lt; 40 lines of code...\nYou just need to keep a reference to the root of the tree outside of the class,\nor wrap it in another class, maybe rename to TreeNode??</p>\n'}, {'answer_id': 2133330, 'author': 'nietras', 'author_id': 98692, 'author_profile': 'https://Stackoverflow.com/users/98692', 'pm_score': 4, 'selected': False, 'text': '<p>See <a href="https://github.com/YaccConstructor/QuickGraph" rel="nofollow noreferrer">https://github.com/YaccConstructor/QuickGraph</a> (previously <a href="http://quickgraph.codeplex.com/" rel="nofollow noreferrer">http://quickgraph.codeplex.com/</a>)</p>\n<p>QuickGraph provides generic directed/undirected graph data structures and algorithms for .NET 2.0 and up. QuickGraph comes with algorithms such as <a href="https://en.wikipedia.org/wiki/Depth-first_search" rel="nofollow noreferrer">depth-first search</a>, <a href="https://en.wikipedia.org/wiki/Breadth-first_search" rel="nofollow noreferrer">breadth-first search</a>, A* search, shortest path, k-shortest path, maximum flow, minimum spanning tree, least common ancestors, etc... QuickGraph supports <a href="https://en.wikipedia.org/wiki/Microsoft_Automatic_Graph_Layout" rel="nofollow noreferrer">MSAGL</a>, <a href="https://en.wikipedia.org/wiki/Microsoft_Automatic_Graph_Layout" rel="nofollow noreferrer">GLEE</a>, and <a href="https://en.wikipedia.org/wiki/Graphviz" rel="nofollow noreferrer">Graphviz</a> to render the graphs, serialization to <a href="https://en.wikipedia.org/wiki/GraphML" rel="nofollow noreferrer">GraphML</a>, etc.</p>\n'}, {'answer_id': 10442244, 'author': 'Ronnie Overby', 'author_id': 64334, 'author_profile': 'https://Stackoverflow.com/users/64334', 'pm_score': 6, 'selected': False, 'text': '<p>Here\'s mine, which is very similar to <a href="https://stackoverflow.com/a/2012855/64334">Aaron Gage\'s</a>, just a little more conventional, in my opinion. For my purposes, I haven\'t ran into any performance issues with <code>List&lt;T&gt;</code>. It would be easy enough to switch to a LinkedList if needed.</p>\n\n<hr>\n\n<pre><code>namespace Overby.Collections\n{\n    public class TreeNode&lt;T&gt;\n    {\n        private readonly T _value;\n        private readonly List&lt;TreeNode&lt;T&gt;&gt; _children = new List&lt;TreeNode&lt;T&gt;&gt;();\n\n        public TreeNode(T value)\n        {\n            _value = value;\n        }\n\n        public TreeNode&lt;T&gt; this[int i]\n        {\n            get { return _children[i]; }\n        }\n\n        public TreeNode&lt;T&gt; Parent { get; private set; }\n\n        public T Value { get { return _value; } }\n\n        public ReadOnlyCollection&lt;TreeNode&lt;T&gt;&gt; Children\n        {\n            get { return _children.AsReadOnly(); }\n        }\n\n        public TreeNode&lt;T&gt; AddChild(T value)\n        {\n            var node = new TreeNode&lt;T&gt;(value) {Parent = this};\n            _children.Add(node);\n            return node;\n        }\n\n        public TreeNode&lt;T&gt;[] AddChildren(params T[] values)\n        {\n            return values.Select(AddChild).ToArray();\n        }\n\n        public bool RemoveChild(TreeNode&lt;T&gt; node)\n        {\n            return _children.Remove(node);\n        }\n\n        public void Traverse(Action&lt;T&gt; action)\n        {\n            action(Value);\n            foreach (var child in _children)\n                child.Traverse(action);\n        }\n\n        public IEnumerable&lt;T&gt; Flatten()\n        {\n            return new[] {Value}.Concat(_children.SelectMany(x =&gt; x.Flatten()));\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 10593721, 'author': 'Jake', 'author_id': 682869, 'author_profile': 'https://Stackoverflow.com/users/682869', 'pm_score': -1, 'selected': False, 'text': '<p>In case you need a rooted tree data structure implementation that uses less memory, you can write your Node class as follows (C++ implementation):</p>\n\n<pre><code>class Node {\n       Node* parent;\n       int item; // depending on your needs\n\n       Node* firstChild; //pointer to left most child of node\n       Node* nextSibling; //pointer to the sibling to the right\n}\n</code></pre>\n'}, {'answer_id': 13430535, 'author': 'Erik Nagel', 'author_id': 1831850, 'author_profile': 'https://Stackoverflow.com/users/1831850', 'pm_score': 3, 'selected': False, 'text': "<p>I have a little extension to the solutions.</p>\n<p>Using a recursive generic declaration and a deriving subclass, you can better concentrate on your actual target.</p>\n<p>Notice, it’s different from a non generic implementation, you don’t need to cast 'node' to 'NodeWorker'.</p>\n<p>Here's my example:</p>\n<pre><code>public class GenericTree&lt;T&gt; where T : GenericTree&lt;T&gt; // recursive constraint\n{\n  // no specific data declaration\n\n  protected List&lt;T&gt; children;\n\n  public GenericTree()\n  {\n    this.children = new List&lt;T&gt;();\n  }\n\n  public virtual void AddChild(T newChild)\n  {\n    this.children.Add(newChild);\n  }\n\n  public void Traverse(Action&lt;int, T&gt; visitor)\n  {\n    this.traverse(0, visitor);\n  }\n\n  protected virtual void traverse(int depth, Action&lt;int, T&gt; visitor)\n  {\n    visitor(depth, (T)this);\n    foreach (T child in this.children)\n      child.traverse(depth + 1, visitor);\n  }\n}\n\npublic class GenericTreeNext : GenericTree&lt;GenericTreeNext&gt; // concrete derivation\n{\n  public string Name {get; set;} // user-data example\n\n  public GenericTreeNext(string name)\n  {\n    this.Name = name;\n  }\n}\n\nstatic void Main(string[] args)\n{\n  GenericTreeNext tree = new GenericTreeNext(&quot;Main-Harry&quot;);\n  tree.AddChild(new GenericTreeNext(&quot;Main-Sub-Willy&quot;));\n  GenericTreeNext inter = new GenericTreeNext(&quot;Main-Inter-Willy&quot;);\n  inter.AddChild(new GenericTreeNext(&quot;Inter-Sub-Tom&quot;));\n  inter.AddChild(new GenericTreeNext(&quot;Inter-Sub-Magda&quot;));\n  tree.AddChild(inter);\n  tree.AddChild(new GenericTreeNext(&quot;Main-Sub-Chantal&quot;));\n  tree.Traverse(NodeWorker);\n}\n\nstatic void NodeWorker(int depth, GenericTreeNext node)\n{                                // a little one-line string-concatenation (n-times)\n  Console.WriteLine(&quot;{0}{1}: {2}&quot;, String.Join(&quot;   &quot;, new string[depth + 1]), depth, node.Name);\n}\n</code></pre>\n"}, {'answer_id': 15101910, 'author': 'Berezh', 'author_id': 721704, 'author_profile': 'https://Stackoverflow.com/users/721704', 'pm_score': 2, 'selected': False, 'text': '<p>Try this simple sample.</p>\n\n<pre><code>public class TreeNode&lt;TValue&gt;\n{\n    #region Properties\n    public TValue Value { get; set; }\n    public List&lt;TreeNode&lt;TValue&gt;&gt; Children { get; private set; }\n    public bool HasChild { get { return Children.Any(); } }\n    #endregion\n    #region Constructor\n    public TreeNode()\n    {\n        this.Children = new List&lt;TreeNode&lt;TValue&gt;&gt;();\n    }\n    public TreeNode(TValue value)\n        : this()\n    {\n        this.Value = value;\n    }\n    #endregion\n    #region Methods\n    public void AddChild(TreeNode&lt;TValue&gt; treeNode)\n    {\n        Children.Add(treeNode);\n    }\n    public void AddChild(TValue value)\n    {\n        var treeNode = new TreeNode&lt;TValue&gt;(value);\n        AddChild(treeNode);\n    }\n    #endregion\n}\n</code></pre>\n'}, {'answer_id': 17995274, 'author': 'Alex Siepman', 'author_id': 1333374, 'author_profile': 'https://Stackoverflow.com/users/1333374', 'pm_score': 2, 'selected': False, 'text': '<p>I created a <a href="http://www.siepman.nl/blog/post/2013/07/30/tree-node-nodes-descendants-ancestors.aspx" rel="nofollow noreferrer">Node&lt;T&gt; class</a> that could be helpful for other people. The class has properties like:</p>\n<ul>\n<li>Children</li>\n<li>Ancestors</li>\n<li>Descendants</li>\n<li>Siblings</li>\n<li>Level of the node</li>\n<li>Parent</li>\n<li>Root</li>\n<li>Etc.</li>\n</ul>\n<p>There is also the possibility to convert a flat list of items with an Id and a ParentId to a tree. The nodes holds a reference to both the children and the parent, so that makes iterating nodes quite fast.</p>\n'}, {'answer_id': 18774221, 'author': 'Grzegorz Dev', 'author_id': 1367449, 'author_profile': 'https://Stackoverflow.com/users/1367449', 'pm_score': 6, 'selected': False, 'text': '<p>Yet another tree structure:</p>\n\n<pre><code>public class TreeNode&lt;T&gt; : IEnumerable&lt;TreeNode&lt;T&gt;&gt;\n{\n\n    public T Data { get; set; }\n    public TreeNode&lt;T&gt; Parent { get; set; }\n    public ICollection&lt;TreeNode&lt;T&gt;&gt; Children { get; set; }\n\n    public TreeNode(T data)\n    {\n        this.Data = data;\n        this.Children = new LinkedList&lt;TreeNode&lt;T&gt;&gt;();\n    }\n\n    public TreeNode&lt;T&gt; AddChild(T child)\n    {\n        TreeNode&lt;T&gt; childNode = new TreeNode&lt;T&gt;(child) { Parent = this };\n        this.Children.Add(childNode);\n        return childNode;\n    }\n\n    ... // for iterator details see below link\n}\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>TreeNode&lt;string&gt; root = new TreeNode&lt;string&gt;("root");\n{\n    TreeNode&lt;string&gt; node0 = root.AddChild("node0");\n    TreeNode&lt;string&gt; node1 = root.AddChild("node1");\n    TreeNode&lt;string&gt; node2 = root.AddChild("node2");\n    {\n        TreeNode&lt;string&gt; node20 = node2.AddChild(null);\n        TreeNode&lt;string&gt; node21 = node2.AddChild("node21");\n        {\n            TreeNode&lt;string&gt; node210 = node21.AddChild("node210");\n            TreeNode&lt;string&gt; node211 = node21.AddChild("node211");\n        }\n    }\n    TreeNode&lt;string&gt; node3 = root.AddChild("node3");\n    {\n        TreeNode&lt;string&gt; node30 = node3.AddChild("node30");\n    }\n}\n</code></pre>\n\n<p><strong>BONUS</strong><br>\nSee fully-fledged tree with:</p>\n\n<ul>\n<li>iterator</li>\n<li>searching</li>\n<li>Java/C#</li>\n</ul>\n\n<p><a href="https://github.com/gt4dev/yet-another-tree-structure" rel="noreferrer">https://github.com/gt4dev/yet-another-tree-structure</a></p>\n'}, {'answer_id': 23150015, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>Here is my implementation of a <a href="https://en.wikipedia.org/wiki/Binary_search_tree" rel="nofollow noreferrer">BST</a>:</p>\n<pre><code>class BST\n{\n    public class Node\n    {\n        public Node Left { get; set; }\n        public object Data { get; set; }\n        public Node Right { get; set; }\n\n        public Node()\n        {\n            Data = null;\n        }\n\n        public Node(int Data)\n        {\n            this.Data = (object)Data;\n        }\n\n        public void Insert(int Data)\n        {\n            if (this.Data == null)\n            {\n                this.Data = (object)Data;\n                return;\n            }\n            if (Data &gt; (int)this.Data)\n            {\n                if (this.Right == null)\n                {\n                    this.Right = new Node(Data);\n                }\n                else\n                {\n                    this.Right.Insert(Data);\n                }\n            }\n            if (Data &lt;= (int)this.Data)\n            {\n                if (this.Left == null)\n                {\n                    this.Left = new Node(Data);\n                }\n                else\n                {\n                    this.Left.Insert(Data);\n                }\n            }\n        }\n\n        public void TraverseInOrder()\n        {\n            if(this.Left != null)\n                this.Left.TraverseInOrder();\n            Console.Write(&quot;{0} &quot;, this.Data);\n            if (this.Right != null)\n                this.Right.TraverseInOrder();\n        }\n    }\n\n    public Node Root { get; set; }\n    public BST()\n    {\n        Root = new Node();\n    }\n}\n</code></pre>\n'}, {'answer_id': 35033913, 'author': 'Meirion Hughes', 'author_id': 1657476, 'author_profile': 'https://Stackoverflow.com/users/1657476', 'pm_score': 2, 'selected': False, 'text': '<p>There is the now released .NET codebase: specifically the code for a <code>SortedSet</code> that implements a <a href="https://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="nofollow noreferrer">red-black tree</a>: <em><a href="https://github.com/Microsoft/referencesource/blob/master/System/compmod/system/collections/generic/sortedset.cs" rel="nofollow noreferrer">sortedset.cs</a></em></p>\n<p>This is, however, a balanced tree structure. So my answer is more a reference to what I believe is the only native tree-structure in the .NET core library.</p>\n'}, {'answer_id': 35208619, 'author': 'Denise Skidmore', 'author_id': 2091951, 'author_profile': 'https://Stackoverflow.com/users/2091951', 'pm_score': 0, 'selected': False, 'text': '<p>If you are going to display this tree on the GUI, you can use <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.treeview(v=vs.100).aspx" rel="nofollow">TreeView</a> and <a href="https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode(v=vs.100).aspx" rel="nofollow">TreeNode</a>.  (I suppose technically you can create a TreeNode without putting it on a GUI, but it does have more overhead than a simple homegrown TreeNode implementation.)</p>\n'}, {'answer_id': 36546817, 'author': 'Ian Ringrose', 'author_id': 57159, 'author_profile': 'https://Stackoverflow.com/users/57159', 'pm_score': 1, 'selected': False, 'text': '<p>Most trees are formed by the data you are processing.</p>\n<blockquote>\n<p>Say you have a <code>person</code> class that includes details of someone’s\n<code>parents</code>, would you rather have the tree structure as part of your\n“domain class”, or use a separate tree class that contained links to\nyour person objects?   Think about a simple operation like getting all\nthe <code>grandchildren</code> of a <code>person</code>, should this code be in the <code>person</code>\nclass, or should the user of the <code>person</code> class have to know about a\nseparate tree class?</p>\n</blockquote>\n<p>Another example is a <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree#Application_in_compilers" rel="nofollow noreferrer">parse tree</a> in a compiler…</p>\n<p>Both of these examples show that the concept of a tree is part of the <strong>domain</strong> of the data and using a separate general-purpose tree at least doubles the number of objects that are created as well as making the API harder to program again.</p>\n<p>We want a way to reuse the standard tree operations, without having to reimplement them for all trees, while at the same time, not having to use a standard tree class. <a href="https://en.wikipedia.org/wiki/Boost_%28C%2B%2B_libraries%29" rel="nofollow noreferrer">Boost</a> has tried to solve this type of problem for C++, but I am yet to see any effect for .NET to get it adapted.</p>\n'}, {'answer_id': 38555544, 'author': 'Ashkan S', 'author_id': 6519111, 'author_profile': 'https://Stackoverflow.com/users/6519111', 'pm_score': 2, 'selected': False, 'text': '<p>I\'ve completed the code that <a href="https://stackoverflow.com/questions/66893/tree-data-structure-in-c-sharp/15101910#15101910">Berezh has shared</a>.</p>\n<pre><code>public class TreeNode&lt;T&gt; : IEnumerable&lt;TreeNode&lt;T&gt;&gt;\n{\n    public T Data { get; set; }\n    public TreeNode&lt;T&gt; Parent { get; set; }\n    public ICollection&lt;TreeNode&lt;T&gt;&gt; Children { get; set; }\n\n    public TreeNode(T data)\n    {\n        this.Data = data;\n        this.Children = new LinkedList&lt;TreeNode&lt;T&gt;&gt;();\n    }\n\n    public TreeNode&lt;T&gt; AddChild(T child)\n    {\n        TreeNode&lt;T&gt; childNode = new TreeNode&lt;T&gt;(child) { Parent = this };\n        this.Children.Add(childNode);\n        return childNode;\n    }\n\n    public IEnumerator&lt;TreeNode&lt;T&gt;&gt; GetEnumerator()\n    {\n        throw new NotImplementedException();\n    }\n\n    IEnumerator IEnumerable.GetEnumerator()\n    {\n        return (IEnumerator)GetEnumerator();\n    }\n}\n\npublic class TreeNodeEnum&lt;T&gt; : IEnumerator&lt;TreeNode&lt;T&gt;&gt;\n{\n\n    int position = -1;\n    public List&lt;TreeNode&lt;T&gt;&gt; Nodes { get; set; }\n\n    public TreeNode&lt;T&gt; Current\n    {\n        get\n        {\n            try\n            {\n                return Nodes[position];\n            }\n            catch (IndexOutOfRangeException)\n            {\n                throw new InvalidOperationException();\n            }\n        }\n    }\n\n    object IEnumerator.Current\n    {\n        get\n        {\n            return Current;\n        }\n    }\n\n    public TreeNodeEnum(List&lt;TreeNode&lt;T&gt;&gt; nodes)\n    {\n        Nodes = nodes;\n    }\n\n    public void Dispose()\n    {\n\n    }\n\n    public bool MoveNext()\n    {\n        position++;\n        return (position &lt; Nodes.Count);\n    }\n\n    public void Reset()\n    {\n        position = -1;\n    }\n}\n</code></pre>\n'}, {'answer_id': 43383944, 'author': 'Dmitry', 'author_id': 7859994, 'author_profile': 'https://Stackoverflow.com/users/7859994', 'pm_score': 2, 'selected': False, 'text': '<p>I have added a complete solution and example using the NTree class above. I also added the &quot;AddChild&quot; method...</p>\n<pre><code>    public class NTree&lt;T&gt;\n    {\n        public T data;\n        public LinkedList&lt;NTree&lt;T&gt;&gt; children;\n\n        public NTree(T data)\n        {\n            this.data = data;\n            children = new LinkedList&lt;NTree&lt;T&gt;&gt;();\n        }\n\n        public void AddChild(T data)\n        {\n            var node = new NTree&lt;T&gt;(data) { Parent = this };\n            children.AddFirst(node);\n        }\n\n        public NTree&lt;T&gt; Parent { get; private set; }\n\n        public NTree&lt;T&gt; GetChild(int i)\n        {\n            foreach (NTree&lt;T&gt; n in children)\n                if (--i == 0)\n                    return n;\n            return null;\n        }\n\n        public void Traverse(NTree&lt;T&gt; node, TreeVisitor&lt;T&gt; visitor, string t, ref NTree&lt;T&gt; r)\n        {\n            visitor(node.data, node, t, ref r);\n            foreach (NTree&lt;T&gt; kid in node.children)\n                Traverse(kid, visitor, t, ref r);\n        }\n    }\n\n    public static void DelegateMethod(KeyValuePair&lt;string, string&gt; data, NTree&lt;KeyValuePair&lt;string, string&gt;&gt; node, string t, ref NTree&lt;KeyValuePair&lt;string, string&gt;&gt; r)\n    {\n        string a = string.Empty;\n        if (node.data.Key == t)\n        {\n            r = node;\n            return;\n        }\n    }\n</code></pre>\n<h3>Using it</h3>\n<pre><code> NTree&lt;KeyValuePair&lt;string, string&gt;&gt; ret = null;\n tree.Traverse(tree, DelegateMethod, node[&quot;categoryId&quot;].InnerText, ref ret);\n</code></pre>\n'}, {'answer_id': 52014730, 'author': 'moien', 'author_id': 5592276, 'author_profile': 'https://Stackoverflow.com/users/5592276', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s my own:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        var tree = new Tree&lt;string&gt;()\n            .Begin("Fastfood")\n                .Begin("Pizza")\n                    .Add("Margherita")\n                    .Add("Marinara")\n                .End()\n                .Begin("Burger")\n                    .Add("Cheese burger")\n                    .Add("Chili burger")\n                    .Add("Rice burger")\n                .End()\n            .End();\n\n        tree.Nodes.ForEach(p =&gt; PrintNode(p, 0));\n        Console.ReadKey();\n    }\n\n    static void PrintNode&lt;T&gt;(TreeNode&lt;T&gt; node, int level)\n    {\n        Console.WriteLine("{0}{1}", new string(\' \', level * 3), node.Value);\n        level++;\n        node.Children.ForEach(p =&gt; PrintNode(p, level));\n    }\n}\n\npublic class Tree&lt;T&gt;\n{\n    private Stack&lt;TreeNode&lt;T&gt;&gt; m_Stack = new Stack&lt;TreeNode&lt;T&gt;&gt;();\n\n    public List&lt;TreeNode&lt;T&gt;&gt; Nodes { get; } = new List&lt;TreeNode&lt;T&gt;&gt;();\n\n    public Tree&lt;T&gt; Begin(T val)\n    {\n        if (m_Stack.Count == 0)\n        {\n            var node = new TreeNode&lt;T&gt;(val, null);\n            Nodes.Add(node);\n            m_Stack.Push(node);\n        }\n        else\n        {\n            var node = m_Stack.Peek().Add(val);\n            m_Stack.Push(node);\n        }\n\n        return this;\n    }\n\n    public Tree&lt;T&gt; Add(T val)\n    {\n        m_Stack.Peek().Add(val);\n        return this;\n    }\n\n    public Tree&lt;T&gt; End()\n    {\n        m_Stack.Pop();\n        return this;\n    }\n}\n\npublic class TreeNode&lt;T&gt;\n{\n    public T Value { get; }\n    public TreeNode&lt;T&gt; Parent { get; }\n    public List&lt;TreeNode&lt;T&gt;&gt; Children { get; }\n\n    public TreeNode(T val, TreeNode&lt;T&gt; parent)\n    {\n        Value = val;\n        Parent = parent;\n        Children = new List&lt;TreeNode&lt;T&gt;&gt;();\n    }\n\n    public TreeNode&lt;T&gt; Add(T val)\n    {\n        var node = new TreeNode&lt;T&gt;(val, this);\n        Children.Add(node);\n        return node;\n    }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Fastfood\n   Pizza\n      Margherita\n      Marinara\n   Burger\n      Cheese burger\n      Chili burger\n      Rice burger\n</code></pre>\n'}, {'answer_id': 64577999, 'author': 'Florian Lavorel', 'author_id': 2594845, 'author_profile': 'https://Stackoverflow.com/users/2594845', 'pm_score': 2, 'selected': False, 'text': '<p>There is also the possibility to use XML with <a href="https://en.wikipedia.org/wiki/Language_Integrated_Query" rel="nofollow noreferrer">LINQ</a>:</p>\n<p><em><a href="https://learn.microsoft.com/en-us/dotnet/standard/linq/create-xml-trees" rel="nofollow noreferrer">Create XML tree in C# (LINQ to XML)</a></em></p>\n<p>XML is the most mature and flexible solution when it comes to using trees and LINQ provides you with all the tools that you need.\nThe configuration of your tree also gets much cleaner and user-friendly as you can simply use an XML file for the initialization.</p>\n<p>If you need to work with objects, you can use XML serialization:</p>\n<p><em><a href="https://learn.microsoft.com/en-us/dotnet/standard/serialization/introducing-xml-serialization" rel="nofollow noreferrer">XML serialization</a></em></p>\n'}, {'answer_id': 64960280, 'author': 'Bar Nuri', 'author_id': 2908786, 'author_profile': 'https://Stackoverflow.com/users/2908786', 'pm_score': -1, 'selected': False, 'text': '<p>Tree With Generic Data</p>\n<pre class="lang-cs prettyprint-override"><code>using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading;\nusing System.Threading.Tasks;\n\npublic class Tree&lt;T&gt;\n{\n    public T Data { get; set; }\n    public LinkedList&lt;Tree&lt;T&gt;&gt; Children { get; set; } = new LinkedList&lt;Tree&lt;T&gt;&gt;();\n    public Task Traverse(Func&lt;T, Task&gt; actionOnNode, int maxDegreeOfParallelism = 1) =&gt; Traverse(actionOnNode, new SemaphoreSlim(maxDegreeOfParallelism, maxDegreeOfParallelism));\n    private async Task Traverse(Func&lt;T, Task&gt; actionOnNode, SemaphoreSlim semaphore)\n    {\n        await actionOnNode(Data);\n        SafeRelease(semaphore);\n        IEnumerable&lt;Task&gt; tasks = Children.Select(async input =&gt;\n        {\n            await semaphore.WaitAsync().ConfigureAwait(false);\n            try\n            {\n                await input.Traverse(actionOnNode, semaphore).ConfigureAwait(false);\n            }\n            finally\n            {\n                SafeRelease(semaphore);\n            }\n        });\n        await Task.WhenAll(tasks);\n    }\n    private void SafeRelease(SemaphoreSlim semaphore)\n    {\n        try\n        {\n            semaphore.Release();\n        }\n        catch (Exception ex)\n        {\n            if (ex.Message.ToLower() != &quot;Adding the specified count to the semaphore would cause it to exceed its maximum count.&quot;.ToLower())\n            {\n                throw;\n            }\n        }\n    }\n\n    public async Task&lt;IEnumerable&lt;T&gt;&gt; ToList()\n    {\n        ConcurrentBag&lt;T&gt; lst = new ConcurrentBag&lt;T&gt;();\n        await Traverse(async (data) =&gt; lst.Add(data));\n        return lst;\n    }\n    public async Task&lt;int&gt; Count() =&gt; (await ToList()).Count();\n}\n\n\n\n</code></pre>\n<p>Unit Tests</p>\n<pre class="lang-cs prettyprint-override"><code>using System.Threading.Tasks;\nusing Xunit;\n\npublic class Tree_Tests\n{\n    [Fact]\n    public async Task Tree_ToList_Count()\n    {\n        Tree&lt;int&gt; head = new Tree&lt;int&gt;();\n\n        Assert.NotEmpty(await head.ToList());\n        Assert.True(await head.Count() == 1);\n\n        // child\n        var child = new Tree&lt;int&gt;();\n        head.Children.AddFirst(child);\n        Assert.True(await head.Count() == 2);\n        Assert.NotEmpty(await head.ToList());\n\n        // grandson\n        child.Children.AddFirst(new Tree&lt;int&gt;());\n        child.Children.AddFirst(new Tree&lt;int&gt;());\n        Assert.True(await head.Count() == 4);\n        Assert.NotEmpty(await head.ToList());\n    }\n\n    [Fact]\n    public async Task Tree_Traverse()\n    {\n        Tree&lt;int&gt; head = new Tree&lt;int&gt;() { Data = 1 };\n\n        // child\n        var child = new Tree&lt;int&gt;() { Data = 2 };\n        head.Children.AddFirst(child);\n\n        // grandson\n        child.Children.AddFirst(new Tree&lt;int&gt;() { Data = 3 });\n        child.Children.AddLast(new Tree&lt;int&gt;() { Data = 4 });\n\n        int counter = 0;\n        await head.Traverse(async (data) =&gt; counter += data);\n        Assert.True(counter == 10);\n\n        counter = 0;\n        await child.Traverse(async (data) =&gt; counter += data);\n        Assert.True(counter == 9);\n\n        counter = 0;\n        await child.Children.First!.Value.Traverse(async (data) =&gt; counter += data);\n        Assert.True(counter == 3);\n\n        counter = 0;\n        await child.Children.Last!.Value.Traverse(async (data) =&gt; counter += data);\n        Assert.True(counter == 4);\n    }\n}\n\n</code></pre>\n'}, {'answer_id': 72226859, 'author': 'ADM-IT', 'author_id': 1143349, 'author_profile': 'https://Stackoverflow.com/users/1143349', 'pm_score': -1, 'selected': False, 'text': "<p>I don't like a tree aproach. It gets things overcomplicated including search or dril-down or even ui controls populating.</p>\n<p>I would suggest to use a very simple approach with <code>IDictionary&lt;TChild, TParent&gt;</code>. This also allows to have no connections between nodes or levels.</p>\n"}]
['https://Stackoverflow.com/questions/66893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/361/']