How can I convert a ConcurrentDictionary to a Dict

2020-06-07 05:01发布

I have a ConcurrentDictionary object that I would like to set to a Dictionary object.

Casting between them is not allowed. So how do I do it?

4条回答
【Aperson】
2楼-- · 2020-06-07 05:05

I think i have found a way to do it.

ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>( );
Dictionary dict= new Dictionary<int, int>( concDict);
查看更多
Summer. ? 凉城
3楼-- · 2020-06-07 05:07

Why do you need to convert it to a Dictionary? ConcurrentDictionary<K, V> implements the IDictionary<K, V> interface, is that not enough?

If you really need a Dictionary<K, V>, you can copy it using LINQ:

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

Note that this makes a copy. You cannot just assign a ConcurrentDictionary to a Dictionary, since ConcurrentDictionary is not a subtype of Dictionary. That's the whole point of interfaces like IDictionary: You can abstract away the desired interface ("some kind of dictionary") from the concrete implementation (concurrent/non-concurrent hashmap).

查看更多
看我几分像从前
4楼-- · 2020-06-07 05:16

The ConcurrentDictionary<K,V> class implements the IDictionary<K,V> interface, which should be enough for most requirements. But if you really need a concrete 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);
查看更多
做自己的国王
5楼-- · 2020-06-07 05:29
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>();
Dictionary<int,string> d = cd.ToDictionary(pair => pair.Key, pair => pair.Value);
查看更多
登录 后发表回答