C#将List转换为Branch

时间:2013-07-23 15:42:23

标签: c# list recursion tree branch

我在C#中有一个字符串列表:

List<string> { "A", "B", "C", "D" };

这些字符串是产品类别的“标题”。

我需要将它们转换为这样的节点分支:

A > B > C > D

列表中项目的顺序决定了它们在分支中的位置,即。 A是根,D是叶节点。

我的对象名为WebBrowseNode,它具有属性:

  • string Titlestring
  • List<WebBrowseNode> Children

我现在已经在这里工作了至少一个小时,并且找不到合适的算法来做这件事。

1 个答案:

答案 0 :(得分:2)

我们的想法是从列表的末尾开始。

WebBrowseNode lastNode = null;
for (int numItem = list.Count - 1; numItem >= 0; numItem--)  // Go from the end to the beginning of the list
{
    string title = myStringList[numItem];

    lastNode = new WebBrowseNode
    {
        Title = title,
        Children = { lastNode }                              // Adds lastNode to the Children list
    };
}

WebBrowseNode root = lastNode;