title: How can I determine if one rectangle is completely contained within another?
body: <p>I have a theoretical grid of overlapping rectangles that might look something like this:</p>
  
  <p><img src="https://i.stack.imgur.com/Isltf.png" alt="grid layout"></p>
  
  <p>But all I have to work with is a collection of Rectangle objects:</p>
  
  <pre><code>var shapes = new List&lt;Rectangle&gt;();
  shapes.Add(new Rectangle(10, 10, 580, 380));
  shapes.Add(new Rectangle(15, 20, 555, 100));
  shapes.Add(new Rectangle(35, 50, 40, 75));
  // ...
  </code></pre>
  
  <p>What I'd like to do is build a DOM-like structure where each rectangle has a ChildRectangles property, which contains the rectangles that are contained within it on the grid.</p>
  
  <p>The end result should allow me to convert such a structure into XML, something along the lines of:</p>
  
  <pre><code>&lt;grid&gt;
    &lt;shape rectangle="10, 10, 580, 380"&gt;
      &lt;shape rectangle="5, 10, 555, 100"&gt;
        &lt;shape rectangle="20, 30, 40, 75"/&gt;
      &lt;/shape&gt;
    &lt;/shape&gt;
    &lt;shape rectangle="etc..."/&gt;
  &lt;/grid&gt;
  </code></pre>
  
  <p>But it's mainly that DOM-like structure in memory that I want, the output XML is just an example of how I might use such a structure.</p>
  
  <p>The bit I'm stuck on is how to efficiently determine which rectangles belong in which.</p>
  
  <p><strong>NOTE</strong> No rectangles are partially contained within another, they're always completely inside another. </p>
  
  <p><strong>EDIT</strong> There will typically be hundreds of rectangles, should I just iterate through every rectangle to see if it's contained by another?</p>
  
  <p><strong>EDIT</strong> Someone has suggested Contains (not my finest moment, missing that!), but I'm not sure how best to build the DOM. For example, take the grandchild of the first rectangle, the parent does indeed contain the grandchild, but it shouldn't be a direct child, it should be the child of the parent's first child.</p>