Welcome to MSDN Blogs Sign in | Join | Help

Mitsu's blog

Discussing topics related to .Net, WPF, C# and Linq
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 ! :-)

Posted: Wednesday, May 07, 2008 12:02 PM by mitsu
Filed under: , ,

Comments

Ian said:

You can optimise this slightly further by using TryGetValue... :)

# May 7, 2008 8:45 AM

Steve said:

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;

   }

}

# May 7, 2008 9:46 AM

Laurent Kempé said:

Funy Mitsu ! I do the same for Request Params.

# May 7, 2008 12:24 PM

mitsu said:

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.

# May 10, 2008 12:02 PM

Sandy Place said:

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

}

# May 22, 2008 5:03 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker