你可以通过两步来做到这一点。第一步 - 从 TreeView 中获取所有节点的列表,即展平 TreeView:
private IEnumerable<TreeNode> Flatten(TreeView treeView)
{
Queue<TreeNode> nodes = new Queue<TreeNode>();
foreach (TreeNode node in treeView.Nodes)
nodes.Enqueue(node);
while (nodes.Any())
{
var current = nodes.Dequeue();
foreach (TreeNode subNode in current.Nodes)
nodes.Enqueue(subNode);
yield return current;
}
}
第二步 - 对节点进行分组并从每个组中删除除第一个节点之外的所有节点:
Flatten(treeView1)
.Cast<CustomFruitCrateNode>()
.GroupBy(n => n.FruitName)
.SelectMany(g => g.Skip(1))
.ToList()
.ForEach(n => n.Remove());