【问题标题】:Build a treeview based on character string基于字符串构建树视图
【发布时间】:2013-02-08 20:25:22
【问题描述】:

我很确定对此有一个简单的答案,但这让我很生气,为什么我无法弄清楚。我正在尝试基于 5 个字符的字符串填充树视图。

public List<string> lst = new List<string>();

lst.Add("10000");
lst.Add("11000");
lst.Add("11100");
lst.Add("12000");
lst.Add("12100");
lst.Add("20000");
lst.Add("21000");
lst.Add("22000");

我正在尝试在这种类型的树中获得上述内容

再说一次,我确信这对许多有经验的 C# 开发人员来说已经是老生常谈了,但我就是想不出一个简单的递归或 linq 解决方案。

【问题讨论】:

  • 你用的是什么树视图 WinForms 或 WPF?请看一下这个链接:social.msdn.microsoft.com/Forums/en/winforms/thread/…
  • 我想我可能歪曲了这个问题。在上面我将值添加到列表中,但实际上这些字符串值已经被分配。我已经创建了一个字符串列表,只是不知道如何将它们分解成树结构。
  • 您在寻找类似于trie 的结构吗?
  • 看看How to create a trie in c#Basic trie data structure implementation (C#)。然后,您可以在创建 trie 后将节点映射到树视图。
  • 不难相信从未听说过这种数据结构,但 trie 数据结构似乎可以扩展以轻松支持树视图

标签: c# winforms linq treeview treenode


【解决方案1】:

这个递归方法应该可以做到:

static TreeNode[] GetNodes(IEnumerable<string> items, string prefix = "")
{
    int preLen = prefix.Length;

    // items that match the current prefix and have a nonzero character right after
    // the prefix
    var candidates = items.Where(i => i.Length > preLen &&
                                      i[preLen] != '0' &&
                                      i.StartsWith(prefix));

    // create nodes from candidates that have a 0 two characters after the prefix.
    // their child nodes are recursively generated from the candidate list
    return candidates.Where(i => i.Length > preLen + 1 && i[preLen + 1] == '0')
                     .Select(i => 
                          new TreeNode(i, GetNodes(candidates, prefix + i[preLen])))
                     .ToArray();
}

你可以像这样调用它:

treeView.Nodes.AddRange(GetNodes(lst));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    相关资源
    最近更新 更多