如何将ConcurrentDictionary转换为Dictionary?

我有一个ConcurrentDictionary对象,我想将其设置为Dictionary对象。

不允许在他们之间施放。 那我该怎么做?

ConcurrentDictionary类实现了IDictionary接口,该接口应该足以满足大多数要求。 但如果你真的需要一个具体的Dictionary ……

 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(yourConcurrentDictionary, yourConcurrentDictionary.Comparer); 

为什么需要将其转换为字典? ConcurrentDictionary实现了IDictionary接口,这还不够吗?

如果你真的需要Dictionary ,你可以使用LINQ 复制它:

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

请注意,这是一个副本 。 您不能只将ConcurrentDictionary分配给Dictionary,因为ConcurrentDictionary不是Dictionary的子类型。 这就是IDictionary这样的接口的全部要点:您可以从具体实现(并发/非并发hashmap)中抽象出所需的接口(“某种字典”)。

我想我找到了办法。

 ConcurrentDictionary concDict= new ConcurrentDictionary( ); Dictionary dict= new Dictionary( concDict); 
 ConcurrentDictionary cd = new ConcurrentDictionary(); Dictionary d = cd.ToDictionary(pair => pair.Key, pair => pair.Value);