Not able to use GetValueorDefault() for Dictionary in C#
Am i missing something ??
You are missing the fact Dictionary
does not contain any method of this name GetValueOrDefault
Dictionary<TKey,TValue> Class
Maybe you are looking for
Dictionary<TKey,TValue>.TryGetValue(TKey, TValue) Method
Gets the value associated with the specified key.
or
ImmutableDictionary.GetValueOrDefault<TKey, TValue> Method (IImmutableDictionary<TKey, TValue>, TKey)
Gets the value for a given key if a matching key exists in the dictionary.
You could however implement your own
public static class Extensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict,TKey key)
=> dict.TryGetValue(key, out var value) ? value : default(TValue);
}
If you are using any of the following, there are extension method overloads for IReadOnlyDictionary
NET 5.0 RC1
.NET Core 3.1 3.0 2.2 2.1 2.0
.NET Standard 2.1
CollectionExtensions.GetValueOrDefault
Tries to get the value associated with the specified key in the dictionary