Removing XElements in a foreach loop

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?


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 (ie 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();
    }
}

在循环逻辑之前创建一个集合,将要删除的元素添加到新集合中,然后调用新集合中每个元素上的items.Remove。


尝试它没有一个而不是foreach。

链接地址: http://www.djcxy.com/p/21324.html

上一篇: 电话号码标准化:任何预先

下一篇: 在foreach循环中删除XElements