Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?

前端 未结 15 1849
暗喜
暗喜 2020-11-27 04:00

The indexer into Dictionary throws an exception if the key is missing. Is there an implementation of IDictionary that instead will return de

15条回答
  •  臣服心动
    2020-11-27 04:52

    Carrying these extension methods can help..

    public static V GetValueOrDefault(this IDictionary dict, K key)
    {
        return dict.GetValueOrDefault(key, default(V));
    }
    
    public static V GetValueOrDefault(this IDictionary dict, K key, V defVal)
    {
        return dict.GetValueOrDefault(key, () => defVal);
    }
    
    public static V GetValueOrDefault(this IDictionary dict, K key, Func defValSelector)
    {
        V value;
        return dict.TryGetValue(key, out value) ? value : defValSelector();
    }
    

提交回复
热议问题