是否有一个IDictionary实现,在缺少键时,返回默认值而不是抛出?

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)

用途:

  • 表达方法(C#6)
  • 一个输出变量(C#7.0)
  • 默认文字(C#7.1)

  • @PeterGluck:更紧凑但效率更低......为什么在键存在的情况下执行两次查找? (29认同)
  • @JonSkeet:谢谢你纠正彼得; 我一直在使用那种"效率较低"的方法,但却没有意识到这一点. (5认同)
  • 非常好!我将无耻地剽窃 - 呃,岔开它.;) (4认同)
  • 显然,MS认为这足以添加到System.Collections.Generic.CollectionExtensions中,就像我刚刚尝试过的那样。 (3认同)
  • 或更紧凑地说:`return(dictionary.ContainsKey(key))吗?dictionary [key]:default(TValue);` (2认同)
  • 仅供参考,@theMayer 的答案仅适用于 .NET Core 2.0+,而不是完整的框架。但是,仍然是一个很好的发现。 (2认同)

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)

  • @nawfal好点.保持干燥比避免一个可怜的方法调用更重要. (3认同)
  • 最后的重载是有趣的.既然没有什么可以选择_from_,这只是一种懒惰的评价形式吗? (2认同)

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)