如何在自定义POCO中使用.NET ConcurrentDictionary的AddOrUpdate?

时间:2014-05-27 12:07:42

标签: c# .net concurrentdictionary

我不确定如何编写func方法的ConcurrentDictionary.AddOrUpdate部分,即检查UpdatedOn属性是否大于或等于现有密钥/值。

鉴于以下POCO,当新项目的日期时间值 GREATER THAN ConcurrentDictionary.AddOrUpdate更新字典中的项目(如果存在) >现有的......否则只是添加它。

(pseduo code)

var results = new ConcurrentDictionary<string, Foo>();

public class Foo
{
    string Id;
    string Name;
    string Whatever;
    DateTime UpdatedOn;
}

我已经looking at the 2nd overloaded methodAddOrUpdate(TKey, TValue, Func<TKey, TValue, TValue>))而且我不确定如何执行该方法的Func部分。

1 个答案:

答案 0 :(得分:2)

有问题的函数参数应该包含该键的键和已存在的值,并返回一个值,该值应该保存在该键中的字典中。

因此,如果您想更新现有值,只需创建一个更新值并返回值而不是新值的函数。


这是一个完整的例子:

var d = new ConcurrentDictionary<string, Foo>();

// an example value
var original_value = new Foo {UpdatedOn = new DateTime(1990, 1, 1)};
d.TryAdd("0", original_value);

var newValue = new Foo {UpdatedOn = new DateTime(2000, 1, 1)};

// try to add the newValue with the same key
d.AddOrUpdate("0", 
              newValue,  
              (key, old_value) => {

                // if the DateTime value is greater,
                // then update the existing value
                if (newValue.UpdatedOn > old_value.UpdatedOn)
                    old_value.UpdatedOn = newValue.UpdatedOn;

                // return old_value, since it should be updated
                // instead of being replaced
                return old_value;
            });

d现在只包含UpdatedOn更新为2000-1-1的原始元素。