Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dictionaries ValueOrNull / ValueorDefault

Currently I'm using

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

I'd like some way to have dictionary[key] return null for nonexistant keys, so I could write something like

var x =  dict[key] ?? defaultValue;

this also winds up being part of linq queries etc. so I'd prefer one-line solutions.

like image 367
Jimmy Avatar asked Oct 31 '08 16:10

Jimmy


3 Answers

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");
    }
}
like image 195
Brian Avatar answered Oct 22 '22 07:10

Brian


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 );
like image 24
TcKs Avatar answered Oct 22 '22 07:10

TcKs


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;
}
like image 5
Mike Chamberlain Avatar answered Oct 22 '22 07:10

Mike Chamberlain