문제

I have a ConcurrentDictionary. I use its AddOrUpdate method to manipulate its items.

My question is: is it possible to use AddOrUpdate's update parameter to contain an if statement? E.g. my ConcurrentDictionary contains objects that has string Id and a DateTime Date properties.

I'd like to - add a new object to it, if the object with the given Id does not exist - update it, if the new object's Date is equal or greater, than the existing one, if it is less, than does not do anything.

In my example:

Dictionary.AddOrUpdate(testObject.Id,testObject,(k, v) => v);

I should change

(k, v) => v

to

if(v.Date >= existingItem.Date) (k, v) => v
else do nothing
도움이 되었습니까?

해결책

v is the value that currently exists in the collection, so to do nothing just return it.

Dictionary.AddOrUpdate(testObject.Id,testObject,(k, v) => 
    (v.Date >= existingItem.Date) ? testObject : v);

More readable:

Dictionary.AddOrUpdate(testObject.Id,testObject,(k, v) => 
{
    if(v.Date >= existingItem.Date) 
        return testObject; 
    else
        return v;
});

다른 팁

A simple way to achieve this would be for your updateValueFactory lambda to return the original value if the new value is not greater:

Dictionary.AddOrUpdate(testObject.Id, testObject,
    (key, value) => testObject.Date > value.Date ? testObject : value);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top