I immediately knew I was going to find an existing method on IDictionary, or write an extension method for this. I couldn’t find an existing one, so I wrote one. Now my code looks like this:

var mappedValue = mapDictionary.Get(value, defaultMapValue);

It takes the key that I want the value for, and a value to return if the key is not found.

IEnumerable has an ElementAtOrDefault method that returns the default value for the type, so I wrote an overload for my method that returns the default value for the type, too. (It returns null for reference types, like strings, and return zero for ints, etc…)

I figured I needed another overload or two that take a Func to get the default value for use in the case where getting the default value is not trivial.

How do you use it? How about I provide a completely contrived example? Let’s say you have this list of state abbreviations and state names that begin with the letter ‘A’ in a Dictionary, but we don’t have the rest of the states: