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

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

    It could be a one-liner to check TryGetValue and return default value if it is false.

     Dictionary myDic = new Dictionary() { { "One", 1 }, { "Four", 4} };
     string myKey = "One"
     int value = myDic.TryGetValue(myKey, out value) ? value : 100;
    

    myKey = "One" => value = 1

    myKey = "two" => value = 100

    myKey = "Four" => value = 4

    Try it online

提交回复
热议问题