title: Get All Children to One List - Recursive C#
body: <p>C# | .NET 4.5 | Entity Framework 5</p>
  
  <p>I have a class in Entity Framework that looks like this:</p>
  
  <pre><code>public class Location
  {
     public long ID {get;set;}
     public long ParentID {get;set;}
     public List&lt;Location&gt; Children {get;set;}
  }
  </code></pre>
  
  <p>ID is the identifier of the location, ParentID links it to a parent, and Children contains all of the children locations of the parent location. I'm looking for some easy way, likely recursively, to get all "Location" and their children to one single List containing the Location.ID's. I'm having trouble conceptualizing this recursively. Any help is appreciated.</p>
  
  <p>This is what I have so far, its an extension to the entity class, but I believe it could be done better/simpler:</p>
  
  <pre><code>public List&lt;Location&gt; GetAllDescendants()
  {
      List&lt;Location&gt; returnList = new List&lt;Location&gt;();
      List&lt;Location&gt; result = new List&lt;Location&gt;();
      result.AddRange(GetAllDescendants(this, returnList));
      return result;
  }
  
  public List&lt;Location&gt; GetAllDescendants(Location oID, ICollection&lt;Location&gt; list)
  {
      list.Add(oID);
      foreach (Location o in oID.Children)
      {
              if (o.ID != oID.ID)
                      GetAllDescendants(o, list);
      }
      return list.ToList();
  }
  </code></pre>
  
  <p><strong>UPDATED</strong></p>
  
  <p>I ended up writing the recursion in SQL, throwing that in a SP, and then pulling that into Entity. Seemed cleaner and easier to me than using Linq, and judging by the comments Linq and Entity don't seem the best route to go. Thanks for all of the help!</p>