3

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
vulkanino
  • 9,074
  • 7
  • 44
  • 71
Tom
  • 3,899
  • 22
  • 78
  • 137

2 Answers2

5

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;
});
M.Babcock
  • 18,753
  • 6
  • 54
  • 84
3

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);
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479