Brad
Brad

Reputation: 25

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.

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

hierarchy

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.

Upvotes: 2

Views: 1368

Answers (1)

JLRishe
JLRishe

Reputation: 101690

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

Upvotes: 1

Related Questions