C # Create TreeView recursively from a list

I currently have a list of elements (Tuple) that were generated programmatically earlier, and now I'm trying to go to the TreeView recursively, but I'm struggling a bit to make it work correctly.

List example: Name | Level

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

So my result should be:

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)

Note. See the answer from LarsTech below for a completely accurate working solution. Thanks!

I deleted the wrong code / attempts and I will leave it all for others who have the same problem.

+4
source share
1 answer

node , , node, :

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

Source: https://habr.com/ru/post/1527701/


All Articles