views:

235

answers:

2

I'd like to be able to specify a default value to return if the key I specify can't be found in the dictionary.

e.g.

int default = 5;
string key = "MyKey";
int foo = myDictionary.GetValue(key, default);

if key is in myDictionary foo should hold the value from the dictionary, otherwise it will hold 5.

+1  A: 

I found a piece of code here which does the job nicely by adding an extension method to IDictionary:

using System.Collections.Generic;

namespace MyNamespace {
    public static class DictionaryExtensions {
        public static V GetValue<K, V>(this IDictionary<K, V> dict, K key) {
            return dict.GetValue(key, default(V));
        }

        public static V GetValue<K, V>(this IDictionary<K, V> dict, K key, V defaultValue) {
            V value;
            return dict.TryGetValue(key, out value) ? value : defaultValue;
        }
    }
}
Lawrence Johnston
A: 

The best way is to use TryGetValue, a possible way is by doing:


    int default = 5;
    string key = "MyKey"; 
    int foo = 0;
    defaultValue = 5;
    (myDictionary.TryGetValue(key, out foo))?return foo: return defaultValue;

If you try to get a value that is not present the TryGetValue returns false, which means that your use the second part of the clause.

You can also decide to set foo to you default value, use the TryGetValue and return foo in any case.

mandel
And why do you like that better than an extension method to IDictionary? (I'm seriously curious here, not trying to impugn your solution)
Lawrence Johnston
from my point of view is to verbose, I undertand that you prefer to add the extension if you know that wou will be using the default value a lot. I'm also not sure the methods should be static...
mandel