Search code examples
c#multithreadinglinqthread-safetyconcurrentdictionary

Adding varying values to a list inside of a Concurrent Dictionary


I have decimals that I'm trying to add to a list inside of a ConcurrentDictionary

ConcurrentDictionary<string, List<decimal>> fullList =
    new ConcurrentDictionary<string, List<decimal>>();

public void AddData(string key, decimal value)
{
    if (fullList.ContainsKey(key))
    {
        var partialList = fullList[key];
        partialList.Add(value);
    }
    else
    {
        fullList.GetOrAdd(key, new List<decimal>() { value });
    }
}

Technically the above code works for me but it was only done that way because I didn't know how to do the GetOrAdd method for both adding and updating. My question is how do I use that method for both considering that my updating would be adding an item to the end of an existing list?


Solution

  • You could use AddOrUpdate method for that purpose, as below:

    fullList.AddOrUpdate(key, 
                         new List<decimal>() { value }, 
                         (key,list) => 
                         { 
                             list.Add(value); 
                             return list; 
                         });
    

    Essentially, when the key is missing a new list is created with only one element, value. Otherwise, we add to the list associated with the current key, the value and we return the list.

    For documentation of this method, please have a look here.