Tip: how to simplify value access from a dictionary ? With an extension method !
I was getting really bored with testing .ContainsKey() at each time I wanted to read a value from a dictionary.
Dictionary<string, string> dico;
if (dico.ContainsKey("key"))
value = dico["key"];
else
value = "default";
A incredibly simple extension method solves this so easily:
public static class MyExtensions
{
public static TValue GetValue<TKey, TValue>(
this IDictionary<TKey, TValue> source,
TKey key, TValue defaultValue)
{
if (source.ContainsKey(key))
return source[key];
else
return defaultValue;
}
}
The call from any dictionary now becomes:
value = dico.GetValue("key", "default");
...sometimes I just wonder how I did not think about such solutions earlier ! :-)
Comments
Anonymous
May 07, 2008
PingBack from http://dictionary.azzblog.info/?p=2354Anonymous
May 07, 2008
You can optimise this slightly further by using TryGetValue... :)Anonymous
May 07, 2008
public static class MyExtensions { public static TValue GetValue<TKey, TValue>( this IDictionary<TKey, TValue> source, TKey key, TValue defaultValue) { TValue result; return source.TryGetValue(key, out result) ? result : defaultValue; } }Anonymous
May 07, 2008
Funy Mitsu ! I do the same for Request Params.Anonymous
May 10, 2008
Thanks for the TryGetValue modification. It is much better using it. The extension method still brings an easier syntax, allowing to be used inside an expression.Anonymous
May 22, 2008
Yet another variation. public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key) { TValue result; return source.TryGetValue(key, out result) ? result : default(TValue); }