代码之家  ›  专栏  ›  技术社区  ›  Jimmy

C#字典值或全值/值或默认值

  •  15
  • Jimmy  · 技术社区  · 17 年前

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

    我想用某种方法让dictionary[key]为不存在的键返回null,这样我就可以编写

    var x =  dict[key] ?? defaultValue;
    

    4 回复  |  直到 17 年前
        1
  •  21
  •   Omer Mor    12 年前

    使用扩展方法:

    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");
        }
    }
    
        2
  •  6
  •   TcKs    17 年前

    您可以使用助手方法:

    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 );
    
        3
  •  5
  •   Mike Chamberlain JaredPar    13 年前

    这里是一个“终极”解决方案,它是作为一个扩展方法实现的,使用IDictionary接口,提供一个可选的默认值,并且编写简洁。

    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;
    }
    
        4
  •  0
  •   Matt Connolly    14 年前

    不仅仅是 TryGetValue(key, out value) 你在找什么?引用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.
    

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