C# dictionaries ValueOrNull / ValueorDefault

后端 未结 4 863
鱼传尺愫
鱼传尺愫 2021-02-13 06:19

Currently I\'m using

var x = dict.ContainsKey(key) ? dict[key] : defaultValue

I\'d like some way to have dictionary[key] return null for nonexi

相关标签:
4条回答
  • 2021-02-13 06:41

    You can use a helper method:

    public abstract class MyHelper {
        public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
            V ret;
            bool found = dic.TryGetValue( key, out ret );
            if ( found ) { return ret; }
            return default(V);
        }
    }
    
    var x = MyHelper.GetValueOrDefault( dic, key );
    
    0 讨论(0)
  • 2021-02-13 06:55

    Here is the "ultimate" solution, in that it is implemented as an extension method, uses the IDictionary interface, provides an optional default value, and is written concisely.

    public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dic, TK key,
        TV defaultVal=default(TV))
    {
        TV val;
        return dic.TryGetValue(key, out val) 
            ? val 
            : defaultVal;
    }
    
    0 讨论(0)
  • 2021-02-13 06:57

    With an extension method:

    public static class MyHelper
    {
        public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic, 
                                                K key, 
                                                V defaultVal = default(V))
        {
            V ret;
            bool found = dic.TryGetValue(key, out ret);
            if (found) { return ret; }
            return defaultVal;
        }
        void Example()
        {
            var dict = new Dictionary<int, string>();
            dict.GetValueOrDefault(42, "default");
        }
    }
    
    0 讨论(0)
  • 2021-02-13 07:02

    Isn't simply TryGetValue(key, out value) what you are looking for? Quoting MSDN:

    When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
    

    from http://msdn.microsoft.com/en-us/library/bb347013(v=vs.90).aspx

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