The*_*edi 116 .net c# hash dictionary
如果缺少键,则Index into Dictionary会引发异常.是否有IDictionary的实现,而是返回默认值(T)?
我知道"TryGetValue"方法,但这不可能与linq一起使用.
这会有效地做我需要的吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
Run Code Online (Sandbox Code Playgroud)
我认为它不会,因为我认为它将迭代键而不是使用哈希查找.
Jon*_*eet 133
实际上,这根本不会有效.
你总是可以写一个扩展方法:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue ret;
// Ignore return value
dictionary.TryGetValue(key, out ret);
return ret;
}
Run Code Online (Sandbox Code Playgroud)
或者使用C#7.1:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key) =>
dictionary.TryGetValue(key, out var ret) ? ret : default;
Run Code Online (Sandbox Code Playgroud)
用途:
naw*_*fal 17
携带这些扩展方法可以帮助..
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key)
{
return dict.GetValueOrDefault(key, default(V));
}
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key, V defVal)
{
return dict.GetValueOrDefault(key, () => defVal);
}
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dict, K key, Func<V> defValSelector)
{
V value;
return dict.TryGetValue(key, out value) ? value : defValSelector();
}
Run Code Online (Sandbox Code Playgroud)
cde*_*dev 10
如果有人使用.net core 2及更高版本(C#7.X),则会引入CollectionExtensions类,并且如果字典中没有key,则可以使用GetValueOrDefault方法获取默认值。
Dictionary<string, string> colorData = new Dictionary<string, string>();
string color = colorData.GetValueOrDefault("colorId", string.Empty);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19190 次 |
| 最近记录: |