Java Map 的“computeIfAbsent”在 C# 字典中相当于什么?

qou*_*all 6 c# java clr

在 Java 中,HashMap 有一个方法computeIfAbsent,如果没有找到该值,则使用给定的函数计算该值。但是,我在 C#'s Dictionary 中没有找到等效的东西。

(TryAdd类似,但如果字典中存在该值,我想避免重新计算该值。)

我可以手动实现它

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;
}
Run Code Online (Sandbox Code Playgroud)

但我不想向核心库写入重复的内容。

小智 1

我认为没有Dictionary同等的东西。它GetValueOrDefault不起作用,因为它不接受函数。我认为扩展函数中的代码与Dictionary. 如果您使用的话,有一个解决方案ConcurrentDictionary;它有GetOrAdd,它可以满足您的要求。从ConcurrentDictionary:

public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
 ...
}
Run Code Online (Sandbox Code Playgroud)

所以像

var dict = new ConcurrentDictionary<string, int>();
dict["blue"] = 3;

var v1 = dict.GetOrAdd("blue", k => k.Length); // v1 == 3

var v2 = dict.GetOrAdd("cerulean", k => k.Length); // v2 == 8
Run Code Online (Sandbox Code Playgroud)

希望这对某人有帮助,因为您现在可能已经继续前进了。

干杯。