IDictionary 如何在删除时获取已删除的项目值

IDictionary How to get the removed item value while removing

我想知道是否可以通过其键删除一个 IDictionary 项并同时 获取其已被删除的实际值?

示例

类似于:

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

普通词典没有这种作为原子操作的功能,但 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}");
}

您可以为普通字典编写一个扩展方法来实现它,但如果您担心它是原子的,那么 ConcurrentDictionary 可能更适合您的用例。

你可以为此写一个扩展方法:

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

这将尝试获取该值,如果它存在,将删除它。否则你应该使用 ConcurrentDictionary 正如其他答案所说。