How can one easily iterate through all nodes in a TreeView, examine their .Checked property and then delete all checked nodes?
It seems straightforward, but you aren't supposed to modify a collection through which you are iterating, eliminating the possibility of a "foreach" loop. (The .Nodes.Remove call is modifying the collection.) If this is attempted, the effect is that only about half of the .Checked nodes are removed.
Even if one were to use two passes: first creating a list of temporary indexes, and then removing by index on the second pass -- the indexes would change upon each removal, invaliding the integrity of the index list.
So, what is the most efficient way to do this?
Here is an example of code that looks good, but actually only removes about half of the .Checked nodes.:
foreach (TreeNode parent in treeView.Nodes)
{
if (parent.Checked)
{
treeView.Nodes.Remove(parent);
}
else
{
foreach (TreeNode child in parent.Nodes)
{
if (child.Checked) parent.Nodes.Remove(child);
}
}
}
(Yes, the intention is only to prune nodes from a tree that is two levels deep.)