【问题标题】:C# Create TreeView recursively from listC#从列表递归创建TreeView
【发布时间】:2014-02-20 07:51:38
【问题描述】:

我目前有一个以前以编程方式生成的项目(元组)列表,我现在正尝试以递归方式将其传递给 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 的回答,以获得完美的工作解决方案。谢谢!

我已经删除了错误的代码/尝试,我将把这一切留给有同样问题的其他人。

【问题讨论】:

  • 这里的“LastNode”到底是什么?那是父节点吗? roots.Add(tree.Nodes.Add("Items")) 还有什么作用? Add 是否返回一个新的 TreeNode?​​span>
  • 你能发布你的TreeItemTreeNodeTreeView类的结构吗?
  • 稍微整理了一下帖子。 LarsTech 提供的答案是完美的。

标签: c# recursion treeview


【解决方案1】:

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

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();

【讨论】:

  • 非常感谢,这绝对完美,轻松解决问题,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-08-23
  • 2021-05-18
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
相关资源
最近更新 更多