Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing XElements in a foreach loop

Tags:

So, I have a bug to remove

foreach (XElement x in items.Elements("x"))  {     XElement result = webservice.method(x);      if (/*condition based on values in result*/)      {         x.Remove();     } } 

The problem is that calling x.Remove() alters the foreach such that if there are two Elements("x"), and the first is removed, the loop doesn't get to the second x element.

So how should I be looping this? Or should this be rewritten another way?

like image 914
CaffGeek Avatar asked Oct 07 '09 16:10

CaffGeek


People also ask

How do I remove an item from a foreach?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

Is foreach readonly?

Unlike the for loop, the iteration variable in a foreach loop is read-only. Attempting to assign a value to the variable within the body of the loop will result in a compile-time error.


1 Answers

I suspect that Linq may be able to help you out here as follows.

using System.Linq;  void foo() {     items.Elements("x")          .Where(x => condition(webservice.method(x)))          .Remove(); } 

If that doesn't work (i.e. the internal enumerator is still invalidated), make a shallow copy of the selected elements and delete them as follows.

using System.Linq;  void foo() {     List xElements = items.Elements("x")                           .Where(x => condition(webservice.method(x)))                           .ToList();      for (int i = xElements.Count - 1; i > -1; i--)     {         xElements[i].Remove();     } } 
like image 199
Steve Guidi Avatar answered Oct 15 '22 04:10

Steve Guidi