【问题标题】:using TryGetValue for nested Dictionary [closed]对嵌套字典使用 TryGetValue [关闭]
【发布时间】:2014-09-20 10:02:33
【问题描述】:

我有这本词典:

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

我如何在其中使用 TryGetValue?

我已经试过了,但它不起作用。

 MyDictionary.TryGetValue(key, out value);

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

【问题讨论】:

  • “不起作用”cannot convert Dictionary&lt;&gt; to string 的一个非常糟糕的替代品。始终包含完整的错误消息。

标签: c# dictionary nested


【解决方案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]);
                }
            }
        }
    }
}

【讨论】:

  • 如何划分“结果”的关键部分和价值部分?
【解决方案2】:

值将是 Dictionary&lt;string, string&gt; 而不是 string 所以你需要

Dictionary<string, string> value;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多