C# dictionaries ValueOrNull / ValueorDefault

后端 未结 4 870
鱼传尺愫
鱼传尺愫 2021-02-13 06:19

Currently I\'m using

var x = dict.ContainsKey(key) ? dict[key] : defaultValue

I\'d like some way to have dictionary[key] return null for nonexi

4条回答
  •  情话喂你
    2021-02-13 06:55

    Here is the "ultimate" solution, in that it is implemented as an extension method, uses the IDictionary interface, provides an optional default value, and is written concisely.

    public static TV GetValueOrDefault(this IDictionary dic, TK key,
        TV defaultVal=default(TV))
    {
        TV val;
        return dic.TryGetValue(key, out val) 
            ? val 
            : defaultVal;
    }
    

提交回复
热议问题