Search code examples
javac#performancedictionary

Update dictionary value and get the previous one in C#


I've came to C# world from Java background.

I need to update the value in a map/dictionary and get the previous value (or null if there were none). I would do the following in Java:

String oldValue = myMap.put(key, newValue);
someFunction(oldValue, newValue);

In C# I use Dictionary, but I've found no method to get the previous value on update. So far I need to perform 2 lookups to accomplish this, which I see not very optimal in terms of performance and lines of code

string oldValue = null;
myDictionary.TryGetValue(key, oldValue);
myDictionary[key] = newValue;
SomeFunction(oldValue, newValue);

Is there an easier way to update value and get the previous one?


Solution

  • public static class DictionaryExtensions
    {
        public static TValue UpdateAndGet<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue newVal)
        {
            TValue oldVal;
            dictionary.TryGetValue(key, out oldVal);
            dictionary[key] = newVal;
    
            return oldVal;
        }
    }