2010-12-02 143 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);