【发布时间】:2011-05-18 20:36:28
【问题描述】:
我有一个 ConcurrentDictionary 对象,我想将它设置为 Dictionary 对象。
不允许在它们之间进行投射。那我该怎么做呢?
【问题讨论】:
标签: c# .net dictionary concurrentdictionary
我有一个 ConcurrentDictionary 对象,我想将它设置为 Dictionary 对象。
不允许在它们之间进行投射。那我该怎么做呢?
【问题讨论】:
标签: c# .net dictionary concurrentdictionary
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);
【讨论】:
IEqualityComparer,不会以这种方式保留!更好:var newDict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, dict.Comparer);
为什么需要将其转换为字典? ConcurrentDictionary<K, V> 实现了IDictionary<K, V> 接口,这还不够吗?
如果你真的需要Dictionary<K, V>,你可以复制使用 LINQ:
var myDictionary = myConcurrentDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
请注意,这是一个副本。您不能只是将 ConcurrentDictionary 分配给 Dictionary,因为 ConcurrentDictionary 不是 Dictionary 的子类型。这就是像 IDictionary 这样的接口的全部意义:您可以从具体实现(并发/非并发 hashmap)中抽象出所需的接口(“某种字典”)。
【讨论】:
我想我已经找到了一种方法。
ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>( );
Dictionary dict= new Dictionary<int, int>( concDict);
【讨论】:
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>();
Dictionary<int,string> d = cd.ToDictionary(pair => pair.Key, pair => pair.Value);
【讨论】: