如何使用.net ConcurrentDictionary's AddOrUpdate与我的自定义POCO

本文关键字:AddOrUpdate 我的 自定义 POCO net 何使用 ConcurrentDictionary | 更新日期: 2023-09-27 18:05:26

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

给定以下POCO,我如何使用。net ConcurrentDictionary.AddOrUpdate来更新字典中的项目(如果它存在),当新项目有一个DateTime值大于现有的一个…否则就直接添加

(pseduo代码)

var results = new ConcurrentDictionary<string, Foo>();
public class Foo
{
    string Id;
    string Name;
    string Whatever;
    DateTime UpdatedOn;
}

我一直在看第二个重载方法(AddOrUpdate(TKey, TValue, Func<TKey, TValue, TValue>)),我只是不确定如何做Func部分的方法。

如何使用.net ConcurrentDictionary's AddOrUpdate与我的自定义POCO

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

所以如果你想更新一个已经存在的值,只需要创建一个函数来更新这个值并返回它,而不是一个新的。


下面是一个完整的例子:

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。