Reputation: 7628
I want to cleanup my custom TreeNode with duplicate custom property when i click on button in win forms application.
For Example I have TreeNodes like this,
public class CustomFruitCrateNode : System.Windows.Forms.TreeNode
{
public string FruitName { get; set; }
public bool EatAble{ get; set; }
}
Now I want to cleanup treeview to remove all duplicate nodes with same FruitName and keep only one.
Upvotes: 1
Views: 865
Reputation: 7628
This is what I did then,
private void bCleanUpTreeView_Click(object sender, EventArgs e)
{
Dictionary<string, string> vDic = new Dictionary<string, string>();
foreach (CustomFruitCrateNode node in treeView1.Nodes)
{
foreach (CustomFruitCrateNode childNode in node.Nodes)
{
if (!vDic.ContainsKey(childNode.FruitName))
{
vdDic.Add(childNode.Location, childNode.FruitName);
}
else
{
childNode.Remove();
}
}
}
}
Upvotes: 0
Reputation: 236248
You can do that it two steps. First step - get list of all nodes from TreeView, i.e. flatten 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;
}
}
And second step - group nodes and remove from each group all nodes except first one:
Flatten(treeView1)
.Cast<CustomFruitCrateNode>()
.GroupBy(n => n.FruitName)
.SelectMany(g => g.Skip(1))
.ToList()
.ForEach(n => n.Remove());
Upvotes: 3