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.
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");
}
}
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 );
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With