更新字典值并获取上一个值

时间:2017-10-09 22:03:55

标签: c# dictionary

我从Java背景来到C#世界。

我需要更新地图/字典中的值并获取之前的值(如果没有,则返回null)。我会在Java中执行以下操作:

String oldValue = myMap.put(key, newValue);
someFunction(oldValue, newValue);

在C#中我使用了Dictionary,但是我发现没有方法可以在更新时获得以前的值。到目前为止,我需要执行2次查找来实现这一点,我认为在性能和代码行方面不是最优的

string oldValue = null;
myDictionary.TryGetValue(key, oldValue);
myDictionary[key] = newValue;
SomeFunction(oldValue, newValue);

是否有更简单的方法来更新价值并获得前一个?

3 个答案:

答案 0 :(得分:5)

public static class DictionaryExtensions
{
    public static TValue UpdateAndGet<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue newVal)
    {
        TValue oldVal;
        dictionary.TryGetValue(key, out oldVal);
        dictionary[key] = newVal;

        return oldVal;
    }
}

答案 1 :(得分:0)

您可以使用从AddOrUpdate继承的“线程安全” ConcurrentDictionary<TKey,TValue>类的内置IDictionary<TKey,TValue>方法,例如:

public static ConcurrentDictionary<string, Country> countries = new ConcurrentDictionary<string, Country>();

public void Main()
{
    Country poland = new Country { Name = "Poland", Capital = "Krakow" };
    countries[poland.Name] = poland; 
    // oops lets update the right capital:
    poland.Capital = "Warsaw";

    myList.AddOrUpdate(poland.Name, poland, (key, existingVal) => 
                                         {
                                             Console.WriteLine($"The old value was: '{existingVal}'");  
                                             return existingVal; 
                                         });
}

//Output: The old value was: 'Krakow'

有关msdn的更多信息。

答案 2 :(得分:-1)

您可以使用扩展方法并编写一个。

以下返回true / false,具体取决于是否找到密钥。

.php

返回旧值。

public static bool UpdateDictionaryAndGetOldValue(this Dictionary<string, string> dict, string key, string newVal, out string oldVal)
{
    oldVal = string.Empty;
    if (dict.TryGetValue(key, out oldVal))
    {
        dict[key] = newVal;
        return true;
    }
    else
        return false;
}

可以使用public static string UpdateDictionaryAndGetOldValue(this Dictionary<string, string> dict, string key, string newVal) { string oldVal = string.Empty; dict.TryGetValue(key, out oldVal); dict[key] = newVal; return oldVal; } TK来实现此概括。

相关问题