C# dictionaries ValueOrNull / ValueorDefault

后端 未结 4 865
鱼传尺愫
鱼传尺愫 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 07:02

    Isn't simply TryGetValue(key, out value) what you are looking for? Quoting MSDN:

    When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
    

    from http://msdn.microsoft.com/en-us/library/bb347013(v=vs.90).aspx

提交回复
热议问题