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

前端 未结 15 1855
暗喜
暗喜 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 05:02

    What about this one-liner that checks whether a key is present using ContainsKey and then returns either the normally retreived value or the default value using the conditional operator?

    var myValue = myDictionary.ContainsKey(myKey) ? myDictionary[myKey] : myDefaultValue;
    

    No need to implement a new Dictionary class that supports default values, simply replace your lookup statements with the short line above.

提交回复
热议问题