15

現在、私は使用しています

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

存在しないキーに対して辞書[キー]がnullを返すようにする方法が欲しいので、次のように書くことができます

var x =  dict[key] ?? defaultValue;

これは linq クエリなどの一部にもなるので、1 行のソリューションをお勧めします。

4

4 に答える 4

21

拡張メソッドを使用する場合:

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");
    }
}
于 2008-10-31T17:02:01.147 に答える
6

ヘルパー メソッドを使用できます。

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 );
于 2008-10-31T16:51:24.943 に答える
5

これは、拡張メソッドとして実装され、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;
}
于 2012-09-28T01:52:53.817 に答える
0

単に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から

于 2012-05-24T23:05:42.087 に答える