Pergunta

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
Foi útil?

Solução

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;
});

Outras dicas

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);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top