In Java, the HashMap has a method computeIfAbsent that, if the value is not found, compute it using the given function. However, I didn't find an equivalent thing in C#'s Dictionary.
( TryAdd is similar but I want to avoid re-computing the value if the value exists in the dictionary.)
I can manually implement it
public static V ComputeIfAbsent<K, V>(this Dictionary<K, V> dict, K key, Func<K, V> generator) {
bool exists = dict.TryGetValue(key, out var value);
if (exists) {
return value;
}
var generated = generator(key);
dict.Add(key, generated);
return generated;
}
But I don't want to write something duplicate to the core library.