title: Fastest way to remove XML nodes with C#
body: <p>Supposed that I have an in-memory XElement as below:</p>
  
  <pre><code>&lt;ROOT&gt;
      &lt;CHILD1 /&gt;
      &lt;CHILD1 /&gt;
      &lt;CHILD2 /&gt;
      &lt;CHILD2 /&gt;
      &lt;CHILD1 /&gt;
      &lt;CHILD1 /&gt;
      &lt;CHILD3 /&gt;
      &lt;CHILD3 /&gt;
  &lt;/ROOT&gt;
  </code></pre>
  
  <p>All CHILD1 nodes must be deleted except the last one.</p>
  
  <p>The tree has approx ~1 million nodes &amp; 70% of them are CHILD1 nodes. What is the most efficient way to remove these unused nodes in a timely fashion? I tried the following:</p>
  
  <pre><code>List&lt;XElement&gt; remNodes = root.Elements("CHILD1").ToList();
  remNodes.RemoveRange(0, remNodes.Length - 1)
  </code></pre>
  
  <p>and also the old &amp; easy way:</p>
  
  <pre><code>XElement[] remNodes = root.Elements("CHILD1").ToArray();
  for (i=0;i&lt;remNodes.Length-1;i++) remNodes[i].Remove();
  </code></pre>
  
  <p>Both took too much time to complete  (~5 hours). Is there any quicker method?</p>
  
  <p><strong>UPDATE 1</strong></p>
  
  <p>Tried to save the last node &amp; remove as below:</p>
  
  <pre><code>XElement savedNode = remNodes.Last();
  savedNode.Save("to_file");
  root.Elements("CHILD1").Remove();
  </code></pre>
  
  <p>But it looks like the time taken is the same.</p>
  
  <p><strong>UPDATE 2</strong></p>
  
  <p>Finally, I'd ended up making the task complete in a timely fashion (less then 1 minute). I used an approach of saving valid nodes to file, then remove the whole tree &amp; reload tree with saved nodes. Thanks @Matthew Haugen for your idea. Would you mind adding your answer?</p>
  
  <p>Thanks.</p>