title: Linq - how to loop a tree data structure to build a tree style object
body: <p>I have the following SQL table data:</p>
  
  <p><img src="https://i.stack.imgur.com/q1sYU.png" alt="enter image description here"></p>
  
  <p>The visual tree should look something like this:</p>
  
  <p><img src="https://i.stack.imgur.com/Pm8J7.png" alt="enter image description here"></p>
  
  <p>To get the very top nodes I'm using:</p>
  
  <pre><code>var parentNodes = data
      .Where(i =&gt; i.AncestorId == i.DescedantId &amp;&amp;
                  (data.Count(d =&gt; d.DescedantId == i.DescedantId) == 1))
      .ToList();
  </code></pre>
  
  <p>Any clue on how to build a function that would loop trough the structure and then build the tree style object?</p>
  
  <p>My tree style object classes are:</p>
  
  <pre><code>public class ProfitCenterRoot
  {
      public List&lt;ProfitCenterItem&gt; Data { get; set; }
  }
  
  public class ProfitCenterItem
  {
      public int AncestorId { get; set; } 
      public int DescendantId { get; set; }
      public string Text { get; set; }
      public bool Leaf { get; set; }
  
      // These are the child items
      public List&lt;ProfitCenterItem&gt; Data { get; set; }
  }
  </code></pre>