Jim*_*mmy 15 .net c# dictionary
目前我正在使用
var x = dict.ContainsKey(key) ? dict[key] : defaultValue
Run Code Online (Sandbox Code Playgroud)
我想要一些方法让字典[key]为非耐用键返回null,所以我可以写类似的东西
var x = dict[key] ?? defaultValue;
Run Code Online (Sandbox Code Playgroud)
这也是linq查询等的一部分,所以我更喜欢单行解决方案.
Bri*_*ian 21
使用扩展方法:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用辅助方法:
public abstract class MyHelper {
public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
V ret;
bool found = dic.TryGetValue( key, out ret );
if ( found ) { return ret; }
return default(V);
}
}
var x = MyHelper.GetValueOrDefault( dic, key );
Run Code Online (Sandbox Code Playgroud)
这是“最终”解决方案,因为它实现为扩展方法,使用IDictionary接口,提供了可选的默认值,并且编写简洁。
public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dic, TK key,
TV defaultVal=default(TV))
{
TV val;
return dic.TryGetValue(key, out val)
? val
: defaultVal;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6667 次 |
| 最近记录: |