Search code examples
c#treenode

What is the algorithm of TreeNode.Nodes.ContainsKey


I am confused about TreeNode.Nodes.ContainsKey(string key) if its searching recursively in its childs for the key, or just searches in its childs only using a regular for loop.
If it recursively searches about the key, is there is a method to search only in its childs?


Solution

  • According to the Reference Source, ContainsKey does the following:

        public virtual bool ContainsKey(string key) {
           return IsValidIndex(IndexOfKey(key)); 
        }
    

    And that method does:

        public virtual int  IndexOfKey(String key) {
            // Step 0 - Arg validation
            if (string.IsNullOrEmpty(key)){
                return -1; // we dont support empty or null keys.
            }
    
            // step 1 - check the last cached item
            if (IsValidIndex(lastAccessedIndex))
            {
                if (WindowsFormsUtils.SafeCompareStrings(this[lastAccessedIndex].Name, key, /* ignoreCase = */ true)) {
                    return lastAccessedIndex;
                }
            }
    
            // step 2 - search for the item
            for (int i = 0; i < this.Count; i ++) {
                if (WindowsFormsUtils.SafeCompareStrings(this[i].Name, key, /* ignoreCase = */ true)) {
                    lastAccessedIndex = i;
                    return i;
                }
            }
    
            // step 3 - we didn't find it.  Invalidate the last accessed index and return -1.
            lastAccessedIndex = -1;
            return -1;
        }
    
        private bool IsValidIndex(int index) {
            return ((index >= 0) && (index < this.Count));
        }
    

    So it appears it just tries to find the index for the key, and if it's valid then that means the key must exist.