C# 字典中与 Java Map 的“computeIfAbsent”等价的是什么?

6
在Java中,HashMap有一个方法叫做computeIfAbsent,如果找不到该值,则使用给定的函数计算它。 但是在C#的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;
}

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

1个回答

1

我认为Dictionary没有等价物。 它的GetValueOrDefault不起作用,因为它不接受函数。 我认为你在扩展函数中的代码是关于Dictionary最好的选择。 如果您使用ConcurrentDictionary,则有一种解决方案;它具有GetOrAdd,可以实现您想要的功能。 来自ConcurrentDictionary

public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
 ...
}

所以类似于这样的东西

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

希望这能帮到某些人,因为你现在可能已经转移了注意力。
干杯。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接