How to Efficiently Delete Checked Items from a TreeView?(如何有效地从 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?
这是一个看起来不错的代码示例,但实际上只删除了大约一半的 .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 中删除选中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何有效地从 TreeView 中删除选中的项目?


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01