title: Get all root elements where any of the children (or grandchildren) meet condition
body: <p>I have a self-referenced hierarchy table in my SQL Database which I imported using EntityFramework database-first. And this is the class I get from it:</p>
  
  <pre><code>public partial class Dimension
  {
      public System.Guid Id { get; set; }
      public string Name { get; set; }
      public Nullable&lt;System.Guid&gt; ParentDimensionId { get; set; }
  
      public virtual ICollection&lt;Dimension&gt; ChildDimensions { get; set; }
      public virtual Dimension ParentDimensions { get; set; }
  }
  </code></pre>
  
  <p>The class and references work perfectely. But now I would like to write a LINQ query that allows me to get all root dimensions <em>(e.g. where the ParentDimensionId == null)</em> for which there are any children that meet a certain condition.</p>
  
  <p>My problem is, that there could be <strong>n number of levels</strong> in this hierarchy and I have to check this condition for every child, grandchild, etc.</p>
  
  <p>So I really need some extension method like this:</p>
  
  <pre><code>List&lt;Dimension&gt; dimensions = db.Dimension.Where(x =&gt;
     x.ParentDimension == null &amp;&amp; // This is the "root" identifier
     x.ChildDimensions.AnyChildWhere( c =&gt; c.Name == "foo") // This is the condition
  ).ToList()
  </code></pre>
  
  <p>This "AnyChildWhere" method would of course need to be able to go through the entire n-level hierarchy tree until there were no children left.</p>
  
  <p>Any ideas?</p>