我目前有一个以编程方式生成的项目列表(Tuple),我现在正试图以递归方式传递给TreeView,但是我正在努力使其正常工作。
列表示例:名称|水平
Fruits | 0
Apples | 1
Green Apples | 2
Golden Delicious | 3
Granny Smith | 3
Cox Orange Pipper | 2
Red Apples | 2
Pink Lady | 3
Red Delicious | 3
Oranges | 1
Blood | 2
Mandarins | 2
Vegetables | 0
Lettuce | 1
Iceberg | 2
Romain | 2
所以我的输出想成为:
Fruits (0)
- Apples (1)
-- Green Apples (2)
--- Granny Smith (3)
--- Golden Delicious (3)
-- Cox Orange Pipper(2)
-- Red Apples (2)
--- Pink Lady (3)
--- Red Delicious (3)
- Oranges (1)
-- Blood (2)
-- Mandarins (2)
Vegetables (0)
- Lettuce (1)
-- Iceberg (2)
-- Romain (2)
注意:请参阅下面LarsTech的答案,了解完美的解决方案。谢谢!
我已经删除了错误的代码/尝试,我会把这一切都留给那些遇到同样问题的人。
答案 0 :(得分:0)
每个节点的“级别”值是您对父级的唯一引用,因此您可以保留级别字典以引用用于该级别的最后一个节点:
Dictionary<int, TreeNode> lastParent = new Dictionary<int, TreeNode>();
foreach (Tuple<string, int> food in foods) {
TreeNodeCollection items;
if (food.Item2 == 0) {
items = treeView1.Nodes;
} else {
items = lastParent[food.Item2 - 1].Nodes;
}
TreeNode treeNode = items.Add(food.Item1);
if (lastParent.ContainsKey(food.Item2)) {
lastParent[food.Item2] = treeNode;
} else {
lastParent.Add(food.Item2, treeNode);
}
}
treeView1.ExpandAll();