Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentDictionary AddOrUpdate a list

I'm trying to use a ConcurrentDictionary to help with a filtering task.

If a number appears in list, then I want to copy an entry from one dictionary to another.

But this part of the AddOrUpdate is not right - v.Add(number)

I get

"Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

And two more errors.

class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        List<int> filter = new List<int> {1,2};
        p.Filter(filter);
    }


    private void Filter(List<int> filter)
    {
        Dictionary<string, List<int>> unfilteredResults = new Dictionary<string, List<int>>();
        unfilteredResults.Add("key1", new List<int> { 1,2,3,4,5});

        ConcurrentDictionary<string, List<int>> filteredResults = new ConcurrentDictionary<string, List<int>>();

        foreach (KeyValuePair<string, List<int>> unfilteredResult in unfilteredResults)
        {
            foreach (int number in unfilteredResult.Value)
            {
                if (filter.Contains(number))
                {
                    filteredResults.AddOrUpdate(unfilteredResult.Key, new List<int> { number }, (k, v) => v.Add(number));
                }
            }
        }
    }
}
like image 703
Bryan Avatar asked Feb 02 '16 23:02

Bryan


People also ask

Is AddOrUpdate thread-safe?

It is thread safe in your usage. It becomes not thread safe when the delegate passed to AddOrUpdate has side effects, because those side effects may be executed twice for the same key and existing value.

How does ConcurrentDictionary work in C#?

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.

Is ConcurrentDictionary GetOrAdd thread-safe?

The GetOrAdd function The vast majority of methods it exposes are thread safe, with the notable exception of one of the GetOrAdd overloads: TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory); This overload takes a key value, and checks whether the key already exists in the database.


1 Answers

Thanks to Lucas Trzesniewski, for pointing out my mistake in the comments - he didn't want to post an answer.

You probably mean: (k, v) => { v.Add(number); return v; }

like image 70
Bryan Avatar answered Sep 29 '22 12:09

Bryan