What happens to C# Dictionary lookup if the key does not exist?

前端 未结 9 1209
感情败类
感情败类 2021-02-01 00:09

I tried checking for null but the compiler warns that this condition will never occur. What should I be looking for?

相关标签:
9条回答
  • 2021-02-01 00:42

    A helper class is handy:

    public static class DictionaryHelper
    {
        public static TVal Get<TKey, TVal>(this Dictionary<TKey, TVal> dictionary, TKey key, TVal defaultVal = default(TVal))
        {
            TVal val;
            if( dictionary.TryGetValue(key, out val) )
            {
                return val;
            }
            return defaultVal;
        }
    }
    
    0 讨论(0)
  • 2021-02-01 00:46

    If you're just checking before trying to add a new value, use the ContainsKey method:

    if (!openWith.ContainsKey("ht"))
    {
        openWith.Add("ht", "hypertrm.exe");
    }
    

    If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

    0 讨论(0)
  • 2021-02-01 00:50

    Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:

    public static class NumbersAdapter
    {
        private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
        {
            ["1"] = "One",
            ["2"] = "Two",
            ["3"] = "Three"
        };
    
        public static string GetValue(string key)
        {
            return Mapping.ContainsKey(key) ? Mapping[key] : key;
        }
    }
    

    Then you can manage the behaviour of this dictionary.

    For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.

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