about summary refs log tree commit diff
path: root/LibMatrix/Extensions/DictionaryExtensions.cs
blob: f01cf681142dbbd46a3fad84a8313bd3c830132b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace LibMatrix.Extensions;

public static class DictionaryExtensions {
    public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict,
        TKey oldKey, TKey newKey) {
        if (!dict.Remove(oldKey, out var value))
            return false;

        dict[newKey] = value; // or dict.Add(newKey, value) depending on ur comfort
        return true;
    }

    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;
    }
}