我如何将同义数转换为词典?
-
30-09-2019 - |
题
我有一个要设置为词典对象的汇总对象。
不允许他们之间的铸造。那我该怎么做呢?
解决方案
这 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);
其他提示
为什么需要将其转换为字典? ConcurrentDictionary<K, V>
实现 IDictionary<K, V>
界面,还不够吗?
如果您真的需要一个 Dictionary<K, V>
, , 你可以 复制 它使用linq:
var myDictionary = myConcurrentDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
请注意,这使得 复制. 。你 不能 只需将同时列表分配给字典,因为contrentDictionary不是字典的子类型。这就是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);
不隶属于 StackOverflow