DictionaryExtensions Class

Provides extension methods for retrieving and converting dictionary values.

public static class DictionaryExtensions

Methods

NameDescription
GetValueOrDefault<TKey, TValue, TResult>(IReadOnlyDictionary<TKey, TValue>, TKey, TResult)Gets a value from the dictionary and converts it to the specified type, or returns a default value if the key is not found or conversion fails.
TryGetValueOrDefault<TKey, TValue, TResult>(IReadOnlyDictionary<TKey, TValue>, TKey, TResult)Attempts to get a value from the dictionary and convert it to the specified type.

GetValueOrDefault<TKey, TValue, TResult>(IReadOnlyDictionary<TKey, TValue>, TKey, TResult)

DictionaryExtensions.cs

Gets a value from the dictionary and converts it to the specified type, or returns a default value if the key is not found or conversion fails.

public static TResult GetValueOrDefault<TKey, TValue, TResult>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key, TResult defaultValue) where TKey : notnull

Type parameters

TKey
The type of keys in the dictionary.
TValue
The type of values in the dictionary.
TResult
The target type to convert the value to.

Parameters

dict IReadOnlyDictionary<TKey, TValue>
The dictionary to retrieve the value from.
key TKey
The key of the value to retrieve.
defaultValue TResult
The value to return if the key is not found or conversion fails.

Returns

TResult The converted value if found and conversion succeeded; otherwise, defaultValue.

TryGetValueOrDefault<TKey, TValue, TResult>(IReadOnlyDictionary<TKey, TValue>, TKey, TResult)

DictionaryExtensions.cs

Attempts to get a value from the dictionary and convert it to the specified type.

public static bool TryGetValueOrDefault<TKey, TValue, TResult>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key, out TResult value) where TKey : notnull

Type parameters

TKey
The type of keys in the dictionary.
TValue
The type of values in the dictionary.
TResult
The target type to convert the value to.

Parameters

dict IReadOnlyDictionary<TKey, TValue>
The dictionary to retrieve the value from.
key TKey
The key of the value to retrieve.
value TResult
When this method returns, contains the converted value if the key was found and conversion succeeded, or the default value if the key was not found or conversion failed.

Returns

bool true if the key was found and conversion succeeded; otherwise, false.