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

时间:2018-08-28 17:01:43

标签: c# idictionary

我想知道是否可以通过其键删除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

2 个答案:

答案 0 :(得分:10)

普通词典没有此功能作为原子操作,而是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可能更适合您的用例。

答案 1 :(得分:6)

您可以为此编写扩展方法:

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作为其他答案。