如果密钥丢失,索引器将抛出异常.是否有IDictionary
的实现会返回default(T)
?
我知道TryGetValue()
方法,但这不可能与LINQ一起使用.
这能有效地满足我的需求吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
我认为它不会,因为我认为它会迭代密钥,而不是使用哈希查找.
如果密钥丢失,索引器将抛出异常.是否有IDictionary
的实现会返回default(T)
?
我知道TryGetValue()
方法,但这不可能与LINQ一起使用.
这能有效地满足我的需求吗?:
myDict.FirstOrDefault(a => a.Key == someKeyKalue);
我认为它不会,因为我认为它会迭代密钥,而不是使用哈希查找.
事实上,这根本不会有效率.
根据 comments ,在.Net Core 2+/NetStandard 2.1+/Net 5MS added the extension method GetValueOrDefault()
对于早期版本,您可以自己编写扩展方法:
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:
public static TValue GetValueOrDefault<TKey,TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key) =>
dictionary.TryGetValue(key, out var ret) ? ret : default;
它使用: