how to remove xmlnode within a foreach loop?

前端 未结 5 1951
北荒
北荒 2021-01-07 04:04

At the following code i use foreach loop to check each node in nodelist and remove some of them. after i remove one node the foreach loop throw the following error: \"The el

5条回答
  •  渐次进展
    2021-01-07 04:36

    The answer, sadly, is to not use foreach, but to fallback on the very bulletproof "for()".

    for(int i = collection.Count - 1; i >= 0; i--)
    {
        object myObject = collection[i];
        collection.Remove(myObject);
    }
    

    In this case, I loop backward in the collection, and remove one object at a time. That way, I can never have an invalid index.

提交回复
热议问题