将TryGetValue用于嵌套字典

时间:2014-09-20 10:02:33

标签: c# dictionary nested

我有这本词典:

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

我如何在此使用TryGetValue?

我试过这个,但它没有用。

 MyDictionary.TryGetValue(key, out value);

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

2 个答案:

答案 0 :(得分:1)

值为Dictionary<string, string>而不是string,因此您需要

Dictionary<string, string> value;

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

然后,您可以在TryGetValue上调用value来查找使用特定字符串键入的值。

答案 1 :(得分: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]);
                }
            }
        }
    }
}
相关问题