title: Group list of objects with corresponding child with multiple inheritance using LINQ
body: <p>I'll summarize the problem using simpler objects. I also belive this is not a duplicate problem.</p>
  <p>I have a flat IEnumerable of Type1 that needs to be converted into an IEnumerable of Type2 where each object contains an IEnumerable of its children. I'm using AutoMapper so mapping from Type1 to Type2 is not a problem. The problem is each children may have children of its own and those grandchildren may have its own children.</p>
  <pre><code>public class Type1
  {
      public int? ParentId { get; set; }
      public int Id { get; set; }
      ...other properties
  }
  
  public class Type2
  {
      public int Id { get; set; }
      public IEnumerable&lt;Type2&gt; Children { get; set; }
      ...other properties
  }
  
  
  
  IEnumerable&lt;Type1&gt; source = GetItems();
  IEnumerable&lt;Type2&gt; result = ...someLinqExpression....;
  </code></pre>
  <p>Is it possible to &quot;un-flat&quot; a list and group the children using linq? Or is there an alternative to using linq with good performance and readibility?</p>
  <p>This is what I have so far:</p>
  <pre><code>        var parents = source
              .Where(element =&gt; element.ParentId == null);
  
          source = source.Except(parents);
  
          parents
              .Select(element =&gt; Mapper.Map&lt;Type2&gt;(element))
              .ToList()
              .ForEach(parent =&gt;
                  parent.Children = source
                  .Where(child =&gt; child.ParentId == parent.Id)
                  .Select(child =&gt; Mapper.Map&lt;Type2&gt;(child)));
  </code></pre>