C#从列表递归创建树视图

C#从列表递归创建树视图,c#,recursion,treeview,C#,Recursion,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

我现在有一个项目列表(元组),这些项目是以前通过编程生成的,我现在正试图递归地传递到树状视图中,但要让它正常工作有点困难

列表示例:名称|级别

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的答案,以获得完美的工作解决方案。谢谢大家!

我已经删除了erroneus代码/尝试,我将把这些留给其他有相同问题的人。

每个节点的“级别”值是对父节点的唯一引用,因此您可以保留一个级别字典,以引用该级别使用的最后一个节点:

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();
Dictionary lastParent=newdictionary();
foreach(食品中的元组食品){
TreeNodeCollection项目;
如果(food.Item2==0){
items=treeView1.节点;
}否则{
items=lastParent[food.Item2-1]。节点;
}
TreeNode TreeNode=items.Add(food.Item1);
if(最后一个父级容器(食品项目2)){
lastParent[食品项目2]=树烯醇;
}否则{
添加(food.Item2,treeNode);
}
}
treeView1.ExpandAll();

这里的“LastNode”到底是什么?那是父节点吗?还有
root.Add(tree.Nodes.Add(“Items”)
做什么?Add是否返回一个新的TreeNode?你能发布你的
TreeItem
TreeNode
TreeView
类的结构吗?这篇文章稍微整理了一下。LarsTech提供的答案是完美的。非常感谢,这绝对是完美的,可以轻松解决问题,我非常感激。