How do you convert a dictionary to a ConcurrentDictionary?

MrM picture MrM · Nov 21, 2014 · Viewed 14.4k times · Source

I have seen how to convert a ConcurrentDictionary to a Dictionary, but I have a dictionary and would like to convert to a ConcurrentDictionary. How do I do that?... better yet, can i set the link statement to be a ConcurrentDictionary?

var customers = _customerRepo.Query().Select().ToDictionary(x => x.id, x => x);

Answer

Habib picture Habib · Nov 21, 2014

Use ConcurrentDictionary<TKey, TValue> Constructor (IEnumerable<KeyValuePair<TKey, TValue>>) constructor which can accept a dictionary object like:

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1,"A");
dictionary.Add(2, "B");

ConcurrentDictionary<int,string> concurrentDictionary = 
             new ConcurrentDictionary<int, string>(dictionary);

can i set the LINQ statement to be a ConcurrentDictionary?

No. You can not.. There is no extension method available to create ConcurrentDictionary in LINQ. You can either create your own extension method or you can use the ConcurrentDictionary constructor in your LINQ query while projecting results.