C# dictionaries ValueOrNull / ValueorDefault

后端 未结 4 871
鱼传尺愫
鱼传尺愫 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:57

    With an extension method:

    public static class MyHelper
    {
        public static V GetValueOrDefault(this IDictionary dic, 
                                                K key, 
                                                V defaultVal = default(V))
        {
            V ret;
            bool found = dic.TryGetValue(key, out ret);
            if (found) { return ret; }
            return defaultVal;
        }
        void Example()
        {
            var dict = new Dictionary();
            dict.GetValueOrDefault(42, "default");
        }
    }
    

提交回复
热议问题