2017-06-25 57 views
2

如果TreeNode.Nodes.ContainsKey(string key)如果它的子對象在鍵上遞歸搜索,或者只是使用常規for循環搜索子對象,我會感到困惑。
如果它遞歸搜索關鍵,是否有一種方法只在其子中搜索?什麼是TreeNode.Nodes.ContainsKey的算法

回答

2

按照Reference SourceContainsKey執行以下操作:

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

這方法做:

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

所以看起來它只是試圖找到一個關鍵的指標,如果它是那麼這就意味着鑰匙必須存在。

+0

謝謝,這是非常有幫助:) –

1

代碼編寫簡單,以獲得第一個節點的關鍵。使用root = true,因此代碼不會檢查頂級節點。代碼可以用於任何不僅僅是樹視圖的根。

 public KeyValuePair<Boolean, TreeNode> SearchChildren(TreeNode node, string key, Boolean root) 
     { 
      if (!root) 
      { 
       if(node.Nodes.ContainsKey(key)) return new KeyValuePair<bool, TreeNode>(true, node.Nodes[key]); 
      } 

      foreach (TreeNode child in node.Nodes) 
      { 
       if (child.Nodes != null) 
       { 
        KeyValuePair<Boolean, TreeNode> results = SearchChildren(child, key, false); 
        if (results.Key) 
        { 
         return results; 
        } 

       } 
      } 
      return new KeyValuePair<bool, TreeNode>(false, null); 
     } 
1

TreeNode.Nodes.ContainsKey(string key)只搜索在其中是TreeNode的直接後代子節點key,且不進行遞歸查詢子節點。

TreeNodeNodes屬性,它是TreeNodeCollection型的,也有Find(string key, bool searchAllChildren)方法,它允許您指定是否要遞歸搜索或只是搜索TreeNode的直接後裔。

例子:假設你有一個叫myTreeNode樹節點...

// search for the key only in direct descendents of myTreeNode 
bool keyIsPresent = myTreeNode.Nodes.ContainsKey("someKey"); 
// value of keyIsPresent will be the same if you specify false 
// for the searchAllChildren parameter in Find 
bool keyIsPresent = myTreeNode.Nodes.Find("someKey", false).Length > 0; 
// value of KeyIsPresent will not necessarily be the same if you 
// specify true for the searchAllChildren parameter in Find, which is 
// recursive and will search all descendents of myTreeNode 
bool keyIsPresent = myTreeNode.Nodes.Find("someKey", true).Length > 0; 

所以Find方法會爲您提供搜索唯一的直接後代,或TreeNode的所有後代的選擇。