4

I found this Extension for C# to convert GetOrAdd to Lazy and I want to do the same for AddOrUpdate.

Can someone help me convert this to AddOrUpdate?

 public static class ConcurrentDictionaryExtensions
{
    public static TValue LazyGetOrAdd<TKey, TValue>(
        this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary,
        TKey key,
        Func<TKey, TValue> valueFactory)
    {
        if (dictionary == null) throw new ArgumentNullException("dictionary");
        var result = dictionary.GetOrAdd(key, new Lazy<TValue>(() => valueFactory(key)));
        return result.Value;
    }


}
Andre DeMattia
  • 631
  • 9
  • 23

1 Answers1

1

It is this:

public static TValue AddOrUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)
{
    if (dictionary == null) throw new ArgumentNullException("dictionary");
    var result = dictionary.AddOrUpdate(key, new Lazy<TValue>(() => addValueFactory(key)), (key2, old) => new Lazy<TValue>(() => updateValueFactory(key2, old.Value)));
    return result.Value;
}

Note the format of the second parameter: a delegate that returns a new Lazy<> object... so from a certain standpoint, it is double-lazy :-)

xanatos
  • 109,618
  • 12
  • 197
  • 280