title: Recursive tree creation
body: <p>I have a <code>Node</code> class in C# with the following properties:</p>
  
  <pre><code>public class Node
  {
     public int Id {get;set;}
     public int? ParentId {get;set;}
     public string Label {get;set;}
  }
  </code></pre>
  
  <p>I have a <code>TreeView</code> control which provides the following method to create
  a new node:</p>
  
  <pre><code>MyTreeView.CreateNode(key, label);
  parent.Nodes.CreateNode(key, label);
  </code></pre>
  
  <p>If I want to add a new child node I need to use the second method otherwise the first one. Both returns an object of type <code>TreeNode</code>.</p>
  
  <p>How would you create in C# a recursive function to populate the treeview considering that the root nodes have <code>ParentId = null</code>?</p>
  
  <p>This is what I have done so far:</p>
  
  <pre><code>// create a list of root nodes
  var roots = myList.Where(x =&gt; x.ParentId == null);
  // send the roots to a recursive func
  foreach(var root in roots)
  {
     AddNode(null,root,myList);
  }
  </code></pre>
  
  <p>this is my recursive function:</p>
  
  <pre><code>private void AddNode(Node parent, Node current, IList&lt;Node&gt; items)
  {
     TreeNode treenode = null;
     if(parent == null)
     {
        treenode = mytree.CreateNode(current.Id.ToString(), current.Label);
     }else{
        var parentnode = mytree.GetNode(parent.Id.ToString());
        treenode = parentnode.Nodes.CreateNode(current.Id.ToString(), current.Label);
     }
     // call the recursion for the children
     var children = items.Where(x =&gt; x.ParentId == current.Id);
     foreach(var child in children)
     {
        AddNode(current, child, items);
     }
  }
  </code></pre>