Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dictionary<> missing key

When i do val = dict["nonexistent key"] i get System.Collections.Generic.KeyNotFoundException Is there a way i have my dictionary call a member function with the key as a param to generate a value?

-edit- Maybe i should of been more specific. I want to AUTOMATICALLY call a member function to do what it needs create the proper value for that key. In this case it makes an entry in my DB then gives me back its unique handle. I'll post below what my solution was.


2 Answers

Use an extension method:

static class DictionaryExtensions {
   public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey,TValue> dic, TKey key, Func<TKey, TValue> valueGenerator) {
      TValue val;
      if (dic.TryGetValue(key, out val))
         return val;
      return valueGenerator(key);
   }
}

You can call it with:

dic.GetValueOrDefault("nonexistent key", key => "null");

Or pass a member function:

dic.GetValueOrDefault("nonexistent key", MyMemberFunction);
like image 94
mmx Avatar answered Dec 23 '25 04:12

mmx


Object value;
if(dict.TryGetValue("nonexistent key", out value))
{
    // this only works when key is found..
}
// no exception is thrown here..
like image 43
Akash Kava Avatar answered Dec 23 '25 02:12

Akash Kava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!