Skip to content

Commit 93cee79

Browse files
committed
Added GetValueOrDefault extension for dictionaries
1 parent 10082d5 commit 93cee79

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/MADE.Collections/DictionaryExtensions.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,29 @@ public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dicti
4949

5050
dictionary.Add(key, value);
5151
}
52+
53+
/// <summary>
54+
/// Gets a value from a dictionary by the specified key, or returns a default value.
55+
/// </summary>
56+
/// <typeparam name="TKey">The type of key item within the dictionary.</typeparam>
57+
/// <typeparam name="TValue">The type of value item within the dictionary.</typeparam>
58+
/// <param name="dictionary">The dictionary to get a value from.</param>
59+
/// <param name="key">The key to get a value for.</param>
60+
/// <param name="defaultValue">The default value to return if not exists. Default, null.</param>
61+
/// <returns>The value if it exists for the key; otherwise, null.</returns>
62+
public static TValue GetValueOrDefault<TKey, TValue>(
63+
this Dictionary<TKey, TValue> dictionary,
64+
TKey key,
65+
TValue defaultValue = default)
66+
{
67+
var result = defaultValue;
68+
69+
if (dictionary != null && dictionary.ContainsKey(key))
70+
{
71+
result = dictionary[key];
72+
}
73+
74+
return result;
75+
}
5276
}
5377
}

0 commit comments

Comments
 (0)