2010-12-02 53 views

答えて

31

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); 
+4

コピーする辞書に、そのように保存されない非デフォルトの「IEqualityComparer」を使用することがあります。 Better: 'var newDict = dict.ToDictionary(kvp => kvp.Key、kvp => kvp.Value、dict.Comparer); ' –

+2

[MSDN](https://msdn.microsoft.com/ja)に注意してください。 -us/library/system.collections.concurrent(v = vs.110).aspx)は、これはスレッドセーフではないと言います。どのようにスレッドセーフなものにしますか? – JonDrnek

+0

実際には、ConcurrentDictionaryのおかげでスレッドセーフです。 ConcurrentDictionaryのコンテンツのスナップショットを取得します。あなたが得た辞書は、後でスレッドセーフではありません。 – Falanwe

9

なぜそれを辞書に変換する必要がありますか? ConcurrentDictionary<K, V>IDictionary<K, V>インターフェイスを実装していますが、十分ではありませんか?

あなたが本当にそれはLINQを使用してすることができます、コピーDictionary<K, V>が必要な場合:

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

注意これはコピーを作ること。 ConcurrentDictionaryは辞書のサブタイプではないので、ConcurrentDictionaryを辞書に割り当てることはできません。それはIDictionaryのようなインターフェイスの全ポイントです。具体的な実装(並行/非並行ハッシュマップ)から、望ましいインターフェイス(「ある種の辞書」)を抽象化することができます。

0
ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>(); 
Dictionary<int,string> d = cd.ToDictionary(pair => pair.Key, pair => pair.Value); 
3

が必要な場合が、私はそれを行うための方法を発見したと思います。

ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>(); 
Dictionary dict= new Dictionary<int, int>(concDict); 
関連する問題