2010-12-02 56 views

回答

31

ConcurrentDictionary<K,V>類實現IDictionary<K,V>接口,該接口對於大多數需求應該足夠了。但是,如果你真的需要一個具體的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); 
+4

請注意,要複製的字典可能會使用非默認的「IEqualityComparer」,它不會以這種方式保留! 更好:`var newDict = dict.ToDictionary(kvp => kvp.Key,kvp => kvp.Value,dict.Comparer);` – 2014-12-01 16:12:37

9

爲什麼你需要將它轉換爲字典? ConcurrentDictionary<K, V>實現了IDictionary<K, V>接口,這是不夠的?

如果你真的需要一個Dictionary<K, V>,你可以複製使用LINQ它:

var myDictionary = myConcurrentDictionary.ToDictionary(entry => entry.Key, 
                 entry => entry.Value); 

注意,這使得複製。你不能只是分配一個ConcurrentDictionary到一個字典,因爲ConcurrentDictionary不是一個字典的子類型。這就是IDictionary這樣的接口的全部要點:您可以從具體實現(併發/非併發哈希映射)中抽象出所需的接口(「某種字典」)。

0
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>(); 
Dictionary<int,string> d = cd.ToDictionary(pair => pair.Key, pair => pair.Value); 
3

我想我已經找到了一種方法來做到這一點。

ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>(); 
Dictionary dict= new Dictionary<int, int>(concDict);