Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a ConcurrentDictionary to a Dictionary?

I have a ConcurrentDictionary object that I would like to set to a Dictionary object.

Casting between them is not allowed. So how do I do it?

like image 548
umbersar Avatar asked Dec 02 '10 00:12

umbersar


People also ask

What is the difference between dictionary and concurrentdictionary?

ConcurrentDictionary was introduced in .NET 4.0 and is available in the System.Collections.Concurrent namespace. It is thread-safe and internally uses locking. It is useful in the case of a multi-threaded application. However, ConcurrentDictionary is slower than Dictionary.

What is the use of concurrency dictionary in Java?

ConcurrentDictionary was introduced in .NET 4.0 and is available in the System.Collections.Concurrent namespace. It is thread-safe and internally uses locking. It is useful in the case of a multi-threaded application.

Can I set the LINQ statement to be a concurrentdictionary?

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..

Is concurrentdictionary thread safe?

As you know, when we are working on real-time projects, then it is possibile to work on a multi-threaded application to add and get items from the dictionary. the result may be wrong because the Dictionary is not thread-safe. ConcurrentDictionary is, by default, thread-safe, which provides the correct result.


1 Answers

The ConcurrentDictionary<K,V> class implements the IDictionary<K,V> interface, which should be enough for most requirements. But if you really need a concrete Dictionary<K,V>...

var newDictionary = yourConcurrentDictionary.ToDictionary(kvp => kvp.Key,                                                           kvp => kvp.Value,                                                           yourConcurrentDictionary.Comparer);  // or... // substitute your actual key and value types in place of TKey and TValue var newDictionary = new Dictionary<TKey, TValue>(yourConcurrentDictionary, yourConcurrentDictionary.Comparer); 
like image 116
LukeH Avatar answered Sep 20 '22 23:09

LukeH