我有一本字典,例如Dictionary<int, string>
如果我知道密钥,获取字符串值的最佳方法是什么?
答案 0 :(得分:18)
如果您知道密钥在字典中:
value = dictionary[key];
如果你不确定:
dictionary.TryGetValue(key, out value);
答案 1 :(得分:10)
你最擅长什么意思?
这是按键访问Dictionary
值的标准方式:
var theValue = myDict[key];
如果该密钥不存在,则会抛出异常,因此您可能希望在获取密钥之前查看它们是否存在(非线程安全):
if(myDict.ContainsKey(key))
{
var theValue = myDict[key];
}
或者,您可以使用myDict.TryGetValue
,但这需要使用out参数才能获取值。
答案 2 :(得分:5)
如果要查询Dictionary集合,可以执行以下操作:
static class TestDictionary
{
static void Main() {
Dictionary<int, string> numbers;
numbers = new Dictionary<int, string>();
numbers.Add(0, "zero");
numbers.Add(1, "one");
numbers.Add(2, "two");
numbers.Add(3, "three");
numbers.Add(4, "four");
var query =
from n in numbers
where (n.Value.StartsWith("t"))
select n.Value;
}
}
你也可以像这样使用n.Key属性
var evenNumbers =
from n in numbers
where (n.Key % 2) == 0
select n.Value;
答案 3 :(得分:4)
var stringValue = dictionary[key];
答案 4 :(得分:3)
你不能做类似的事情:
var value = myDictionary[i];
?
答案 5 :(得分:3)
string value = dictionary[key];
答案 6 :(得分:2)
Dictionary.TryGetValue
是最安全的方式
或使用字典索引器作为其他建议,但记得抓住KeyNotFoundException
答案 7 :(得分:2)
嗯,我不太确定你在这里问的是什么,但我想这是关于字典的?
如果您知道密钥,则很容易获得字符串值。
string myValue = myDictionary[yourKey];
如果您想像索引器一样使用(如果此词典在类中),您可以使用以下代码。
public class MyClass
{
private Dictionary<string, string> myDictionary;
public string this[string key]
{
get { return myDictionary[key]; }
}
}