title: Recursive Hierarchical Parent child
body: <p>I have a collection of items coming from a database which has a <code>parentid</code> value or null.</p>
  
  <p>Here is my class design:</p>
  
  <pre><code>public class Item
  {
  public int id{get;set;}
  public string Name{get;set;}
  public int? ParentId{get;set;}
  public List&lt;Item&gt; SubItems{get;set;}
  }
  </code></pre>
  
  <p>I want to build a hierarchical structure of Items from the collection. Assume a collection is 100 items from which I need to construct the structure based on the ParentId mapping.</p>
  
  <p>I tried this post <a href="http://www.superstarcoders.com/blogs/posts/recursive-hierarchical-joins-in-c-sharp-and-linq.aspx" rel="nofollow noreferrer">Recursive Hierarchical Joins in C# and LINQ</a>
   but it gives me an error if ParentId is null.</p>
  
  <p>Also tried <a href="https://stackoverflow.com/questions/15867478/build-tree-type-list-by-recursively-checking-parent-child-relationship-c-sharp">Build tree type list by recursively checking parent-child relationship C#</a> , but this solution also does not work for me.</p>
  
  <p>How do I achieve this?</p>