How can I convert a ConcurrentDictionary to a Dictionary?

umbersar picture umbersar · Dec 2, 2010 · Viewed 27.1k times · Source

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?

Answer

LukeH picture LukeH · Dec 2, 2010

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);