Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert values in ConcurrentDictionary

Tags:

c#-4.0

I'm trying to insert values into ConcurrentDictionary, I'm used to dictionary, so this is 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 correct way, hence I'm doing this into class.

like image 201
Mark Avatar asked Dec 06 '22 22:12

Mark


1 Answers

Collection initializers are syntactic sugar for calls to a public Add() method ... which ConcurrentDictionary doesn't provide - it has an AddOrUpdate() method instead.

An alternative you can use is an intermediate Dictionary<> passed to the constructor overload that accepts an 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 infered from initializers.

like image 179
LBushkin Avatar answered Feb 19 '23 19:02

LBushkin