سؤال

وحاليا أنا أستخدم

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

وأود بعض طريقة لجعل القاموس [مفتاح] العودة لاغية لمفاتيح nonexistant، حتى أتمكن من كتابة شيء مثل

var x =  dict[key] ?? defaultValue;

وهذه الرياح أيضا أن تكون جزءا من الاستفسارات LINQ وما إلى ذلك حتى انني افضل الحلول من سطر واحد.

هل كانت مفيدة؟

المحلول

مع طريقة التمديد:

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");
    }
}

نصائح أخرى

ويمكنك استخدام أسلوب مساعد:

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 );

وهنا هو "نهاية المطاف" الحل في أن يتم تنفيذ ذلك كطريقة الإرشاد، ويستخدم واجهة 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;
}

وأليس 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. كوم / EN-US / مكتبة / bb347013 (ت = vs.90) .aspx اتصال

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top