Dictionary<K,V>.GetValueOrDefault()
If you attempt to get a value from a dictionary using a key that doesn't exist, it throws a KeyNotFoundException. But this extension method to return a default value when the key doesn't exist. Also supports an overload with a Lazy initialization of the fallback value.
Source
static class Extensions {
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) where TKey : notnull {
ArgumentNullException.ThrowIfNull(dictionary);
return dictionary.TryGetValue(key, out var value) ? value : defaultValue;
}
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, Lazy<TValue> defaultValue) where TKey : notnull {
ArgumentNullException.ThrowIfNull(dictionary);
return dictionary.TryGetValue(key, out var value) ? value : defaultValue.Value;
}
}
Example
Dictionary<int, string> dictionary = new()
{
{ 1, "foo" }
};
Console.WriteLine(dictionary.GetValueOrDefault(1, "not found")); // foo
Console.WriteLine(dictionary.GetValueOrDefault(2, "not found")); // not found
Console.WriteLine(dictionary.GetValueOrDefault(3, new Lazy<string>("not found"))); // not found
Author: Fons Sonnemans
Submitted on: 14 jul. 2023
Language: csharp
Type: dictionary-tkey-tvalue
Views: 1594