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
As you're not simply removing items from the collection you're looping over, I'm not sure if "use a for loop" will work.
The following takes two steps:
public static XmlNodeList Scan(XmlNodeList nodeList)
{
List<XmlNode> toRemove = new List<XmlNode>();
foreach (XmlNode xmlElement in nodeList)
{
string elementValue = xmlElement.InnerText;
if (elementValue.Length < 6 || elementValue.Substring(0, 3) != "999")
{
toRemove.Add(xmlElement);
}
}
foreach(XmlNode xmlElement in toRemove)
{
XmlNode node = xmlElement.ParentNode;
node.RemoveChild(xmlElement);
}
return nodeList;
}
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.
Use for loop instead from
for(I=length-1;I>=0;I--)
For each is used for enumerating and you cannot delete while enumerating the list. Also the loop must start from the last element to avoid any shift when you delete an element.
I found an alterative: Convert xmlnodelist to list<>
XmlNodeList
has a method Cast
and can be used as follows:
var listOfNodes = new List<XmlNode>(xmlNodeList.Cast<XmlNode>());
You are not allowed to change a collection used during a foreach
iteration. You can use For..loop
instead
for(int i=0; i<nodeList.Length; i++)
{
//remove nodeList[i];
}