Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDictionary How to get the removed item value while removing [duplicate]

Tags:

c#

idictionary

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?

Example

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}");
}

Output

//We have just remove value1
like image 290
Shahar Shokrani Avatar asked Aug 28 '18 17:08

Shahar Shokrani


2 Answers

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.

like image 161
Marie Avatar answered Oct 10 '22 19:10

Marie


You could write an extension method for this:

public static class DictionaryExtensions
{
    public static bool TryRemove<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, out TValue value)
    {
        if (dict.TryGetValue(key, out value))
            return dict.Remove(key);
        else
            return false;
    }
}

This will attempt to get the value and if it exists, will remove it. Otherwise you should use a ConcurrentDictionary as the other answer said.

like image 26
Ron Beyer Avatar answered Oct 10 '22 20:10

Ron Beyer