umb*_*sar 23 .net c# dictionary concurrentdictionary
我有一个ConcurrentDictionary对象,我想将其设置为Dictionary对象.
不允许在他们之间施放.那我该怎么做?
Luk*_*keH 37
本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);
Run Code Online (Sandbox Code Playgroud)
Hei*_*nzi 13
为什么需要将其转换为字典?ConcurrentDictionary<K, V>
实现IDictionary<K, V>
接口,是不够的?
如果你真的需要Dictionary<K, V>
,你可以使用LINQ 复制它:
var myDictionary = myConcurrentDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个副本.您不能只将ConcurrentDictionary分配给Dictionary,因为ConcurrentDictionary不是Dictionary的子类型.这就是IDictionary这样的接口的全部要点:您可以从具体实现(并发/非并发hashmap)中抽象出所需的接口("某种字典").
我想我已经找到了办法.
ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>( );
Dictionary dict= new Dictionary<int, int>( concDict);
Run Code Online (Sandbox Code Playgroud)