小编典典

是否有一个IDictionary实现,在缺少键的情况下返回默认值而不是抛出异常?

c#

如果缺少键,则字典中的索引器将引发异常。是否有IDictionary的实现将返回default(T)的实现?

我知道“ TryGetValue”方法,但是不能与linq一起使用。

这会有效地满足我的需求吗:

myDict.FirstOrDefault(a => a.Key == someKeyKalue);

我认为它不会像我想的那样会迭代键,而不是使用哈希查找。


阅读 497

收藏
2020-05-19

共1个答案

小编典典

确实,那根本不会有效。

您总是可以编写扩展方法:

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;

使用:

  • 表示形式的方法(C#6)
  • 输出变量(C#7.0)
  • 默认文字(C#7.1)
2020-05-19