【问题标题】:IDictionary How to get the removed item value while removing [duplicate]IDictionary如何在删除时获取已删除的项目值[重复]
【发布时间】:2018-08-28 17:01:43
【问题描述】:

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

【问题讨论】:

  • 不,没有。当密钥不存在时会发生什么?
  • @RonBeyer Remove 在密钥不存在时返回 false。
  • @JonathonChase 我知道,但是out removed 包含什么? null? default(T)?
  • @RonBeyer 我已经更新了我的问题,我目前的设计可以使用null
  • @RonBeyer 我希望 default(T) 与 TryXYZ 模式一样,但你说得对,它需要定义。

标签: c# idictionary


【解决方案1】:

普通字典没有这个功能作为原子操作,而是ConcurrentDictionary&lt;TKey,TValue&gt;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 可能更适合您的用例。

【讨论】:

    【解决方案2】:

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

    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 作为另一个答案。

    【讨论】:

    • value = default(TValue);
    • 这绝对是个人喜好,但如果默认分配发生在 return false 之前,可能会更容易理解,因为这是唯一一次使用它。
    • @RufusL 7.3 可以推断,在这种情况下不需要。
    • @RufusL 实际上我也想问这个问题。我很惊讶我错过了这个功能,谢谢你的提醒!
    • 酷,所以整个事情可以简化为return dict.TryGetValue(key, out value) &amp;&amp; dict.Remove(key);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2015-10-30
    • 2014-12-31
    相关资源
    最近更新 更多