Best way to handle a KeyNotFoundException

后端 未结 6 1459
再見小時候
再見小時候 2021-01-31 01:26

I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the

6条回答
  •  终归单人心
    2021-01-31 01:55

    One line solution using TryGetValue

    string value = dictionary.TryGetValue(key, out value) ? value : "No key!";
    

    Be aware that value variable must be of type which dictionary returns in this case string. Here you can not use var for variable declaration.

    If you are using C# 7, in which case you CAN include the var and define it inline:

    string value = dictionary.TryGetValue(key, out var tmp) ? tmp : "No key!";
    

    Here is also nice extension method which will do exactly what you want to achieve dict.GetOrDefault("Key") or dict.GetOrDefault("Key", "No value")

    public static TValue GetOrDefault(this Dictionary dictionary, TKey key, TValue defaultValue = default(TValue))
    {
          if (dictionary != null && dictionary.ContainsKey(key))
          {
               return dictionary[key];
          }
          return defaultValue;
     }
    

提交回复
热议问题