diff options
Diffstat (limited to 'MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs')
-rw-r--r-- | MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs b/MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs index c51baec..78bbdfa 100644 --- a/MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs +++ b/MatrixRoomUtils.Core/Extensions/DictionaryExtensions.cs @@ -10,4 +10,24 @@ public static class DictionaryExtensions { dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort return true; } -} \ No newline at end of file + + public static Y GetOrCreate<X, Y>(this IDictionary<X, Y> dict, X key) where Y : new() { + if (dict.TryGetValue(key, out var value)) { + return value; + } + + value = new Y(); + dict.Add(key, value); + return value; + } + + public static Y GetOrCreate<X, Y>(this IDictionary<X, Y> dict, X key, Func<X, Y> valueFactory) { + if (dict.TryGetValue(key, out var value)) { + return value; + } + + value = valueFactory(key); + dict.Add(key, value); + return value; + } +} |