IDictionary How to get the removed item value while removing

  • A+

I would like to know if it is possible to remove an IDictionary item by its key and in the same time get its actual value that has been removed?


something like:

Dictionary<string,string> myDic = new Dictionary<string,string>(); myDic["key1"] = "value1";  string removed; if (nameValues.Remove("key1", out removed)) //No overload for this... {     Console.WriteLine($"We have just remove {removed}"); } 


//We have just remove value1 


Normal dictionaries don't have this functionality as an atomic operation but a ConcurrentDictionary<TKey,TValue> does.

ConcurrentDictionary<string,string> myDic = new ConcurrentDictionary<string,string>(); myDic["key1"] = "value1";  string removed; if (myDic.TryRemove("key1", out removed)) {     Console.WriteLine($"We have just remove {removed}"); } 

You could write an extension method for a normal dictionary to implement this but if you are concerned about it being atomic a ConcurrentDictionary is probably more correct for your use case.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: