Alir Kahi
Alir Kahi

Reputation: 1300

Going back one iteration in foreach loop in C#

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.

Upvotes: 3

Views: 5125

Answers (4)

Wim Ombelets
Wim Ombelets

Reputation: 5265

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.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

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

Upvotes: 3

Codor
Codor

Reputation: 17605

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.

Upvotes: 5

qqbenq
qqbenq

Reputation: 10460

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.

Upvotes: 0

Related Questions