title: Create a nested list of items from objects with a parent reference
body: <p>I am using <code>C#</code> and I have a list of items that have a nullable parent ID property.  </p>
  
  <p>I need to convert this to a list of items that have a list of their children and keep going down generations until there are no items left.</p>
  
  <p>My existing class  </p>
  
  <pre><code>public class Item
  {
      public int Id { get; set; }
      public int? ParentId { get; set; }
  }
  </code></pre>
  
  <p>My first thoughts...</p>
  
  <p>Create a class</p>
  
  <pre><code>public class ItemWithChildren
  {
      public Item Item { get; set; }
      public List&lt;ItemWithChildren&gt; Children { get; set; }
  }  
  </code></pre>
  
  <p>Now I need some way to get a <code>List&lt;ItemWithChildren&gt;</code> that has all the top level Item objects and their children into the <code>Children</code> property. </p>
  
  <p>Note that the nesting is not a set number of levels.  </p>
  
  <p>I was hoping there was an elegant LINQ query that would work. So far I just have this...  </p>
  
  <pre><code>var itemsWithChildren = items.Select(a =&gt; new ItemWithChildren{ Item = a });
  </code></pre>