Question

I have a foreach loop that iterates different levels of a treeView in C# that its simplified version looks like this:

foreach (TreeNode childNode in currentNode.Nodes)
{
    if (!someCondition)
    {
        currentNode.Remove();                    
    }
}   

but the problem is that when a node (for example from a list of node1, node2, node3 and node4) is removed the list becomes shorter and the foreach loop skips one iteration (for example, say if node2 was to be removed the list becomes node1, node3 and node4 and the next node that the foreach loop considers will be node4 instead of node3). This is because the framework is storing these nodes in an array/list so I would like to know if it is possible to make a foreach loop go back one iteration when I want to remove a node from the tree.

I'm pretty new in .NET framework so your help is really appreciated.

Was it helpful?

Solution 2

You can use for loop here:

// Pay attention to reversed order:
// each currentNode.Remove() changes currentNode.Nodes.Count 
for (int i = currentNode.Nodes.Count - 1; i >= 0; --i)  {
  TreeNode childNode = currentNode.Nodes[i];

  if (!someCondition) {
    currentNode.Remove();                    
  }
}

OTHER TIPS

The desired result can perhaps be achieved using Linq by setting

currentNode.Nodes = currentNode.Nodes.Where( n => SomeCondition( n ) ).ToList();

or something similar, so no explicit iteration is necessary. A less elegant solution is using an explicit for-loop running backwards, so that the loop index cannot become invalid. However I would consider this bad practice when a more structural approach is available.

No this is not possible because the iterations of a foreach loop aren't "indexed" in a strict sense.
A for loop is, however, indexed because you provide it with a counting mechanism yourself. There you can change your counter.

Usually it's not a great idea to modify the collection that you are iterating through within a foreach. You should consider using a for loop instead and manually keep track of the current index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top