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

前端 未结 15 1753
暗喜
暗喜 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

    Collections.Specialized.StringDictionary provides a non-exception result when looking up a missing key's value. It is also case-insensitive by default.

    Caveats

    It is only valid for its specialized uses, and — being designed before generics — it doesn't have a very good enumerator if you need to review the whole collection.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 05:05

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

     Dictionary<string, int> myDic = new Dictionary<string, int>() { { "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

    0 讨论(0)
提交回复
热议问题