2015-03-02 150 views
1

我正在創建一個字典並將字符串添加爲鍵和另一個字典作爲引用特定用戶的值。 我無法迭代鍵(字典中的字符串),如果符合我的要求,我需要獲取該字典中的值。在C中迭代字典#

喜歡的東西:

Dictionary<string,Dictionary<string,string>> myDictionary = new Dictionary<string,Dictionary<string,string>> 
mydictionary.Add(string,Dictionary<string,string>) 

這裏就是我想要做的:

foreach(string s in Dictionary<string,Dictionary>) 
{ if(s.contains("Foo")) { 
     return the dictionary which is mapped to this key. 
} 
} 
+0

使用'的foreach(字符串s在mydictionary.Keys)' – danludwig 2015-03-02 13:53:07

+3

你確定使用字典是最好的方法?如果你只是想重複它,那麼可能有更好的選擇?取決於你當然在哪裏/如何使用它! – Belogix 2015-03-02 13:53:09

+0

你想檢查's.ContainsKey(「foo」)'這也看起來很糟糕,爲什麼不使用具有屬性的類。 – 2015-03-02 13:53:19

回答

0

像這樣的事情?

foreach (var s in myDictionary.Keys) 
{ 
    if (s.Contains("Foo")) 
     return myDictionary[s]; 
} 
+0

在這個例子中,s是一個字符串,所以它適用於s.Contains – MariusUt 2015-03-02 14:00:46

4

這裏有一個LINQ的一行應該做你需要什麼...

return myDictionary 
    .Where(kvp => kvp.Key.Contains("Foo")) 
    .Select(kvp => kvp.Value) 
    .FirstOrDefault(); 
+0

@CoderofCode因爲這不是OP想要做的。他們正在尋找鑰匙內的***子串***。可能存在類似於類似於類似結構的結構,但這會超出此問題的範圍。 – spender 2015-03-02 14:00:28

+0

是的,我在再次查看問題後得到了這個結果。這就是爲什麼刪除評論。 – 2015-03-02 14:12:24

1

如果你只是想返回內部字典(值),你應該使用TryGetValue,這是最佳的性能,明智的:

Dictionary<string, string> values; 
if (dictionary.TryGetValue("Foo", out values) && values != null) 
{ 
    // do something with the value 
} 

如果不能滿足您的需求,您可以遍歷鍵,或者通過鍵值對,根據您的需要:

foreach (KeyValuePair<string, Dictionary<string, string>> kvp in dictionary) 
{ 
    if(kvp.Key.Contains("Foo")) 
    { 
     var dictionary = kvp.Value; 
    } 
} 
-1

試試這種方法。

foreach(DictionaryEntry Item in myDictionary){ 
    Console.WrileLine("Name : "+ Item.Key+" Value"+Item.value.toString()); 
} 
+0

謝謝大家的幫助,我選擇了適合我需求的解決方案之一。 – SriSri 2015-03-02 14:24:50

0
Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>(); 

      Dictionary<String, string> di = new Dictionary<string, string>(); 
      di.Add("1", "Hello1"); 
      myDictionary.Add("Item1", di); 

      di.Add("2", "Hello2"); 
      myDictionary.Add("Item2", di); 

      di.Add("3", "Hello3"); 
      myDictionary.Add("Item3", di); 


      var result = myDictionary.Where(c => c.Key == "Item1").FirstOrDefault(); 
      if (result.Key != null) 
      { 
       Dictionary<string, string> output = result.Value; 
      }