Ana*_*nth 6 .net c# asp.net dictionary
例如,我有一本字典Dictionary<int, string>.
如果我知道密钥,获取字符串值的最佳方法是什么?
Joe*_*Joe 18
如果您知道密钥在字典中:
value = dictionary[key];
Run Code Online (Sandbox Code Playgroud)
如果您不确定:
dictionary.TryGetValue(key, out value);
Run Code Online (Sandbox Code Playgroud)
Ode*_*ded 10
什么是最好的意思?
这是按键访问值的标准方法Dictionary:
var theValue = myDict[key];
Run Code Online (Sandbox Code Playgroud)
如果密钥不存在,则会抛出异常,因此您可能希望在获取密钥之前查看它们是否存在(非线程安全):
if(myDict.ContainsKey(key))
{
var theValue = myDict[key];
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用myDict.TryGetValue,但这需要使用out参数才能获得值.
如果要查询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;
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以像这样使用n.Key属性
var evenNumbers =
from n in numbers
where (n.Key % 2) == 0
select n.Value;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13744 次 |
| 最近记录: |