C# dictionaries ValueOrNull / ValueorDefault

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

    You can use a helper method:

    public abstract class MyHelper {
        public static V GetValueOrDefault( Dictionary dic, K key ) {
            V ret;
            bool found = dic.TryGetValue( key, out ret );
            if ( found ) { return ret; }
            return default(V);
        }
    }
    
    var x = MyHelper.GetValueOrDefault( dic, key );
    

提交回复
热议问题