0

I want to create a hierarchical view of strings based on first two characters.

If the strings are: AAAA,AAAA,BBDD,AABB,AACC,BBDD,BBEE

I want to reate a treeview that looks like this:

AA  
  AAAA  
  AABB
  AACC 
BB
  BBDD
  BBEE

I currently have some code that looks like this (inside a loop over the strings):

    TreeNode pfxNode;

    if (treeView1.Nodes[pfx]!=null) {
        pfxNode = treeView1.Nodes[pfx];
    }
    else {
        pfxNode = treeView1.Nodes.Add(pfx);
    }

    if (!pfxNode.Nodes.ContainsKey(string)) {
        pfxNode.Nodes.Add(string, string + " some info");
    }

For some reason this ends up with multiple "AA" nodes at the top level.
What am I missing?

please no pre-filtering of strings I want to be able to check if a specific treenode exists based on its key.

thanks

epeleg
  • 10,347
  • 17
  • 101
  • 151

2 Answers2

2
else {
    pfxNode = treeView1.Nodes.Add(pfx);
}

There's your mistake, you are forgetting to set the key of the tree node. So the next ContainsKey() won't find it. Fix:

    pfxNode = treeView1.Nodes.Add(pfx, pfx);
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This is definately what I was missing. I expected that pfx would also become the key when a single string is provided. thanks. – epeleg Jun 11 '11 at 14:01
0

Use this:

var q = from s in arr
        group s by s.Substring(0, 2) into g
        select new
        {
            Parent = g.Key,
            Children = g.Select (x => x).Distinct()
        };

foreach (var item in q)
{
    var p = new TreeNode(item.Parent);
    TreeView1.Nodes.Add(p);
    foreach (var item2 in item.Children)
        p.Nodes.Add(new TreeNode(item2));
}
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • although the answer provided by @Hans Passant solved my Problem I am still interested in your answer as well. This is LINQ syntax - right? could you provide some details on how this should work ? also is there any performance or other advantage to this syntax? – epeleg Jun 11 '11 at 14:05
  • also I was not able to run add this code to my program, it does not seem to know what var is and keeps saying that many ;'s are missing along this text block. should I install something to make this work ? – epeleg Jun 11 '11 at 14:08
  • @epeleg You need .NET >= 3.5 for Linq and `var` key word to work. As for performance linq `group by` and `distinct` operation are pretty good. – Magnus Jun 11 '11 at 15:16