Insert Values ​​in ConcurrentDictionary

I am trying to insert values ​​into a ConcurrentDictionary, I am using a dictionary, so this does not work:

public ConcurrentDictionary<string, Tuple<double, bool,double>> KeyWords = new ConcurrentDictionary<string, Tuple<double, bool,double>> { {"Lake", 0.5, false, 1} }; 

What is the right way, so I do it in class.

+4
source share
2 answers

Collection initializers are syntactic sugar for calls to the public Add() method ... which ConcurrentDictionary does not provide - it has AddOrUpdate() instead.

An alternative you can use is an intermediate Dictionary<> passed to the constructor overload, which accepts IEnumerable<KeyValuePair<K,V>> :

 public ConcurrentDictionary<string, Tuple<double, bool,double>> KeyWords = new ConcurrentDictionary<string, Tuple<double, bool,double>>( new Dictionary<string,Tuple<double,bool,double>> { {"Lake", Tuple.Create(0.5, false, 1.0)}, } ); 

Note. I corrected your example to use Tuple.Create() , since tuples are not output from initializers.

+10
source

You can use the initializer dictionary :

 var dict = new ConcurrentDictionary<int, string> { [0] = "zero", [1] = "one", }; 

Yes, I know the question is

+3
source

Source: https://habr.com/ru/post/1345162/


All Articles