User089 User089 - 1 year ago 76
C# Question

For loop iterates half time in C#

In following snippet, I am trying to hide child node of a tree if there value does not exists in the list. Currently, I've 63 child nodes but the loop iterates for top 32 values. I couldn't make it running for full number of child nodes. I will be thankful if you suggest to diagnose the problem.

for (int i = 0; i < docTree.Nodes[0].ChildNodes.Count; i++)
if (tempList.Contains(docTree.Nodes[0].ChildNodes[i].Value))

else {

Answer Source

When you start you have 63 nodes if you removeAt(0) then you have 62 nodes and i will increment to 1. The node that was previously at index 1 is now at index 0 and will be skipped. Your for loop never actually looks at that node. This repeats in a way that you will only check half of the nodes. You should start at the last index and decrement back to zero so that removing a node won't impact the nodes in the list you haven't checked yet.

You should always watch for a for loop iterating over a list or array and modifying it in the loop. Many hairy situations can arise when this happens.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download