目前我使用的是
var x = dict.ContainsKey(key) ? dict[key] : defaultValue
我想一些办法让词典[关键]返回了不存在的密钥空,这样我就可以写的东西像
I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like
var x = dict[key] ?? defaultValue;
这也蜿蜒被LINQ查询等,所以我想preFER一个在线解决方案的一部分。
this also winds up being part of linq queries etc. so I'd prefer one-line solutions.
通过一个扩展方法:
public static class MyHelper
{
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic,
K key,
V defaultVal = default(V))
{
V ret;
bool found = dic.TryGetValue(key, out ret);
if (found) { return ret; }
return defaultVal;
}
void Example()
{
var dict = new Dictionary<int, string>();
dict.GetValueOrDefault(42, "default");
}
}
上一篇:执行查询超过6次后,Node.js停止监听(卡住)Node、js
下一篇:System.Timers.Timer的的线程安全VS System.Threading.Timer线程、安全、Timers、System