我想知道是否可以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}");
}
Run Code Online (Sandbox Code Playgroud)
//We have just remove value1
Run Code Online (Sandbox Code Playgroud)
Mar*_*rie 10
普通词典没有像原子操作那样的功能,但ConcurrentDictionary<TKey,TValue> 确实如此.
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}");
}
Run Code Online (Sandbox Code Playgroud)
你可以编写一个普通字典的扩展方法来实现它,但是如果你担心它是原子的,那么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;
}
}
Run Code Online (Sandbox Code Playgroud)
这将尝试获取值,如果存在,将删除它.否则你应该用ConcurrentDictionary另一个答案说.