I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the
One line solution using TryGetValue
string value = dictionary.TryGetValue(key, out value) ? value : "No key!";
Be aware that value variable must be of type which dictionary returns in this case string. Here you can not use var for variable declaration.
If you are using C# 7, in which case you CAN include the var and define it inline:
string value = dictionary.TryGetValue(key, out var tmp) ? tmp : "No key!";
Here is also nice extension method which will do exactly what you want to achieve dict.GetOrDefault("Key") or dict.GetOrDefault("Key", "No value")
public static TValue GetOrDefault(this Dictionary dictionary, TKey key, TValue defaultValue = default(TValue))
{
if (dictionary != null && dictionary.ContainsKey(key))
{
return dictionary[key];
}
return defaultValue;
}