title: Plain DataSource to Nested Lists c#
body: <p>It all starts with a Stored Procedure data result <em>(plain structure)</em>:</p>
  
  <blockquote>
    <p><em>IdGrandad, GrandadName, IdDad, DadName, IdChild, ChildName</em></p>
  </blockquote>
  
  <p><em>The response should be a nested entities list.</em></p>
  
  <p><br />
  I get the data into a <strong>SqlDataReader</strong>... then, here comes the loop:</p>
  
  <pre><code>var grandadList = new List&lt;Grandad&gt;();
  
  while (reader.Read())
  {
      // Properties setters.
      Grandad grandadItem = BindGrandad(reader);
      Dad dadItem = BindDad(reader);
      Child childItem = BindChild(reader);
  
      // Entities finders.
      Func&lt;Grandad, bool&gt; foundGrandad = (item =&gt; item.Identity.Equals(grandadItem.Identity));
      Func&lt;Dad, bool&gt; foundDad = (item =&gt; item.Identity.Equals(dadItem.Identity));
  
      if (!grandadList.Any(foundGrandad))
          grandadList.Add(grandadItem);
  
      // Here comes the horror-code...
      if (!grandadList.Where(foundGrandad).SelectMany(item =&gt; item.DadList).ToList().Any(foundDad))
          grandadList.SingleOrDefault(foundGrandad)?
              .DadList.Add(dadItem);
  
      grandadList.SingleOrDefault(foundGrandad)?
          .DadList.SingleOrDefault(foundDad)?
          .ChildList.Add(childItem);
  }
  </code></pre>
  
  <p><br />
  <br />
  Any idea of how can I simplify the loop code?</p>
  
  <p><strong>Thanks in advance!</strong></p>