[英]Build a treeview based on character string
I'm pretty sure there is a simple answer to this, but it's killing me why I cant figure this out. 我很确定对此有一个简单的答案,但这使我无法解决这个问题。 I'm trying to populate a treeview based on a 5-character string.
我正在尝试基于5个字符的字符串填充treeview。
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");
I'm trying to get the above in this type of tree 我试图在这种类型的树中获得以上
Again, I'm sure it is old hat to many experienced C# developers, but I just can't figure out a simple recursive or linq solution. 再次重申,对于许多有经验的C#开发人员来说,它肯定是旧帽子,但是我只是想不出一个简单的递归或linq解决方案。
This recursive method should do it: 这种递归方法应该做到这一点:
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();
}
You can just invoke it like this: 您可以像这样调用它:
treeView.Nodes.AddRange(GetNodes(lst));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.