2

これには簡単な答えがあると確信していますが、なぜ私がこれを理解できないのか、それは私を殺します。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ソリューションを理解することはできません。

4

1 に答える 1

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));
于 2013-02-23T07:40:39.640 に答える