views:

68

answers:

3

Hi. I'm looking for an efficient little algorithm to traverse the text property of a .NET treeView node list. When the user is finished adding new nodes and eventually hits save I need to check that the text property (that contains the user entered friendly name) is still unique.
Life would be easy if the treeView key happened to be this datum, but it is not (its a GUID, but gotta let the users enter a friendly name).

Any better ideas than a introducing a new method with a foreach loop to check for duplicate names in the text property for every one of the nodes? BTW - I already have each individual node available in the current codepath...I'm traversing the list once to look for other (easier) conditions to offer feedback on. foreach (TreeNode node in treeView.Nodes[0].Nodes) { ... }

Thanks, Bob

+2  A: 

If the user builds the tree from scratch then if you insert each name into a Hashtable you can quickly check for duplicates by checking for the existence of the name in the Hashtable. You'll have to handle updates but that's easy enough.

Arnshea
I think you are right. A list wont work. The uniqueness is actually within within different types of members of the treeView (quick check I can do after finding a dupe name) so I can put the type in a hash along with the name.
Bob
A: 

I had to do this once. As I recall, I subclassed the TreeView and its nodes and then added my own methods to catch any changes to the text property that would always add the new value to a List, which of course would throw an error if that text value already existed. Alos, any old/prev node.text values had to be removed form the List first before the new value was added.

This worked fine for me.

RBarryYoung
A: 

I don't know what your elegance-to-maintainability ratio is, but for something this straightforward I'd consider a hashtable like Arnshea mentioned, or even something as simple as a SortedList.

overslacked