是否有 IDictionary 实现,在缺少键时,返回默认值而不是抛出? [英] Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
问题描述
如果键丢失,Dictionary
的索引器会抛出异常.是否有 IDictionary
的实现而不是返回 default(T)
?
The indexer into Dictionary
throws an exception if the key is missing. Is there an implementation of IDictionary
that instead will return default(T)
?
我知道 TryGetValue()
方法,但它不可能与 LINQ 一起使用.
I know about the TryGetValue()
method, but that's impossible to use with LINQ.
这能有效地满足我的需求吗?:
Would this efficiently do what I need?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
我认为不会,因为我认为它会迭代键而不是使用哈希查找.
I don't think it will as I think it will iterate the keys instead of using a Hash lookup.
推荐答案
确实,那根本没有效率.
Indeed, that won't be efficient at all.
根据评论,在 .Net Core 2+/NetStandard 2.1+/Net 5 中,MS 添加了扩展方法 GetValueOrDefault()
As per comments, in .Net Core 2+ / NetStandard 2.1+ / Net 5, MS added the extension method GetValueOrDefault()
对于早期版本,您可以自己编写扩展方法:
For earlier versions you can write the extension method yourself:
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;
}
或使用 C# 7.1:
Or with C# 7.1:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key) =>
dictionary.TryGetValue(key, out var ret) ? ret : default;
使用:
- 一种表达体的方法(C# 6)
- 输出变量 (C# 7.0)
- 默认文字(C# 7.1)
这篇关于是否有 IDictionary 实现,在缺少键时,返回默认值而不是抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!