2013-02-23 124 views
2

一個TreeView我敢肯定有一個簡單的答案,但它的殺了我,爲什麼我不能想出解決辦法。我正在嘗試基於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"); 

我試圖讓上述這種類型的樹

hierarchy

再次,我敢肯定,這是舊帽子,許多有經驗的C#開發,但我可以」找出一個簡單的遞歸或linq解決方案。

+0

你在使用你的TreeView的WinForms或WPF?請看看這個鏈接:http://social.msdn.microsoft.com/Forums/en/winforms/thread/dae1c72a-dd28-4232-9aa4-5b38705c0a97 – 2013-02-23 06:40:35

+0

對不起使用的WinForms – Brad 2013-02-23 06:49:57

+0

我想我可能已經歪曲了問題。在上面我將值添加到列表中,但實際上這些字符串值已被分配。我已經儘可能創建一個字符串列表,但不知道如何將它們分解爲樹結構。 – Brad 2013-02-23 07:04:55

回答

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

JLRishe感謝代碼的完美工作。謝謝.. – Brad 2013-02-23 08:06:17