none
How to add a new element to a hashset that is value of a ConcurrentDictionary? RRS feed

  • Question

  • I have a ConcurrentDictionary that has as key a long and as value a hashset of int. I want that if the key isn't in the dictionary, add a new hashset with the first element. If the key exists, add the new element to the existing dictionary.

    I am trying something like that:

    ConcurrentDictionary<long, HashSet<int>> myDic = new ConcurrentDictionary<long, HashSet<int>>();
    int myElement = 1;
    myDic.AddOrUpdate(1, new Hashset<int>(){myFirstElement},
    (key, actualValue) => actualValue.Add(myElement));

    The problem with this code is the third parameter, because .Add() method returns a bool and the AddOrUpdate expects a hashset. The first and second parameters are right.

    So my question is how I can add a new element to the hashset in thread-safe way and avoid duplicates (it is the reason why I am using a hashset as value). The problem of the hashset is that it is not thread-safe and if I get it first and later add the new element, I am doing outside of the dictionary and I could have problems.

    Thanks.

    Tuesday, October 31, 2017 10:41 AM

Answers

  • Hello ComptonAlvaro,

    >>The problem with this code is the third parameter, because .Add() method returns a bool and the AddOrUpdate expects a hashset

    Just modify the third parameter as Anonymous function.

      myDic.AddOrUpdate(1, new HashSet<int>() { myElement },
                (key, actualValue) => { actualValue.Add(myElement); return actualValue;});

    Or

    Func<long,HashSet<int>,HashSet<int>> func = delegate (long x,HashSet<int> y) {
                    y.Add(myElement);return y;
                };
    
                myDic.AddOrUpdate(1, new HashSet<int>() { myElement }, func);

    Sincerely,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by ComptonAlvaro Friday, November 10, 2017 8:52 AM
    Tuesday, November 7, 2017 10:56 AM
    Moderator