about summary refs log tree commit diff
path: root/LibMatrix/Extensions/DictionaryExtensions.cs
blob: fbc5cf539ea084a89ce5a2fadad4b1e05dabb268 (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
33
namespace LibMatrix.Extensions;

public static class DictionaryExtensions {
    public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict,
        TKey oldKey, TKey newKey) {
        TValue value;
        if (!dict.Remove(oldKey, out 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;
    }
}