如何有效地删除一个TreeView选中的项目? [英] How to Efficiently Delete Checked Items from a TreeView?
问题描述
怎么能够通过一个TreeView的所有节点很容易重复,审视自己的.Checked属性,然后删除所有选中的节点?
How can one easily iterate through all nodes in a TreeView, examine their .Checked property and then delete all checked nodes?
这看起来非常简单,但你不应该修改通过其进行迭代的集合,消除了foreach循环的可能性。 (该.Nodes.Remove呼叫被修改的集合。)如果此尝试,其效果是,只有大约一半的.Checked节点被去除。
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?
下面是code,看起来很不错的例子,但实际上只删除大约一半的.Checked节点:
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.)
推荐答案
这将删除节点列举它们后,可以递归地用于n层节点。
This will remove the nodes after enumerating them, and can be used recursively for n-tiers of nodes.
void RemoveCheckedNodes(TreeNodeCollection nodes)
{
List<TreeNode> checkedNodes = new List<TreeNode>();
foreach (TreeNode node in nodes)
{
if (node.Checked)
{
checkedNodes.Add(node);
}
else
{
RemoveCheckedNodes(nodes.ChildNodes);
}
}
foreach (TreeNode checkedNode in checkedNodes)
{
nodes.Remove(checkedNode);
}
}
这篇关于如何有效地删除一个TreeView选中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!