2014-09-20 102 views
0

我有这个词典:使用TryGetValue嵌套字典

private Dictionary<int, Dictionary<string, string>> MyDictionary = new Dictionary<int, Dictionary<string, string>>(); 

如何使用TryGetValue在这?

我试过这个,但它不起作用。

MyDictionary.TryGetValue(key, out value); 

key是一个整数,value是一个空字符串。

+2

_“不起作用”_是一个非常糟糕的替代品,无法将Dictionary <>转换为字符串。始终包含完整的错误消息。 – 2014-09-20 10:42:22

回答

1

您将按以下方式使用。

我正在收回正确的价值。请执行相同的操作。

using System; 
using System.Collections.Generic; 

namespace ConsoleApplication3 
{ 
    public class Program 
    { 
     public static void Main() 
     { 
      var dictionary = new Dictionary<int, Dictionary<string, string>>(); 
      var value = new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }; 
      dictionary.Add(1, value); 

      Dictionary<string, string> result; 


      if (dictionary.TryGetValue(1, out result)) 
      { 
       foreach (var key in result.Keys) 
       { 
        Console.WriteLine("Key: {0} Value: b{1}", key, result[key]); 
       } 
      } 
     } 
    } 
} 
+0

我如何划分“结果”的关键部分和值部分? – dieKoderin 2014-09-21 05:25:38

+0

是的thanx很多! – dieKoderin 2014-09-21 09:46:22

1

值将是一个Dictionary<string, string>不是string所以你需要

Dictionary<string, string> value; 

if (MyDictionary.TryGetValue(key, out value)) 
{ 
    // do something with value 
} 

然后,你可以调用TryGetValuevalue找到一个特定的字符串键的值。