【问题标题】:How can I use a .NET ConcurrentDictionary's AddOrUpdate with my custom POCO?如何在我的自定义 POCO 中使用 .NET ConcurrentDictionary 的 AddOrUpdate?
【发布时间】:2014-05-27 12:07:42
【问题描述】:

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

鉴于以下 POCO,当新项目的 DateTime 值大于时,我如何使用 .NET ConcurrentDictionary.AddOrUpdate 更新字典中的项目(如果存在)现有的...否则它只是添加它。

(伪代码)

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

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

我一直是 looking at the 2nd overloaded method (AddOrUpdate(TKey, TValue, Func&lt;TKey, TValue, TValue&gt;)),只是不知道如何执行该方法的 Func 部分。

【问题讨论】:

  • 您使用ConcurrentDictionay的关键和价值是什么

标签: c# .net concurrentdictionary


【解决方案1】:

所讨论的函数参数应接受键和该键的现有值,并返回一个值,该值应保存在该键的字典中。

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


这是一个完整的例子:

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 的原始元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多