dictionary - How do I add a Python-style Get() method which takes a default value to my C# dictionaries? -


If I can not find the given key in that, then I want to be able to specify a default value to go back dictionary.

For example

  int default = 5; String key = "mike"; Int foo = myDictionary.GetValue (key, default);  

If the key is in myDictionary foo , then it should grab it by value, otherwise it should be Will 5

I have found a piece of code that does the job well, an extension method for IDictionary Add:

  using System.Collections.Generic; Nameshot My Namespace {Public Static Class Dictionary Extensions (Public Static V gate value & lieutenant; K, V & gt; (This id Works & lt; K, V> Dixon, Key Key) {return dict.GetValue (Key, Default (V)); } Public Static G GetValue & lt; K, V> (This is idictionary & lt; k, v> dict, k key, v default value) {V value; Return dict.TryGetValue (key, value out)? Price: defaultValue; }}}  

Comments