我有一本字典:
private Dictionary<int, Dictionary<string, string>> MyDictionary = new Dictionary<int, Dictionary<string, string>>();我如何在其中使用TryGetValue?
我试过了,但不起作用。
MyDictionary.TryGetValue(key, out value);键是整数,值是空字符串。
发布于 2014-09-20 10:19:12
您将以下列方式使用。
我要拿回正确的价值。请执行同样的命令。
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]);
}
}
}
}
}发布于 2014-09-20 10:05:36
值将是Dictionary<string, string>而不是string,因此您需要
Dictionary<string, string> value;
if (MyDictionary.TryGetValue(key, out value))
{
// do something with value
}然后,您可以在TryGetValue上调用value,以找到一个具有特定字符串键的值。
https://stackoverflow.com/questions/25947578
复制相似问题