【问题标题】:How can I convert a ConcurrentDictionary to a Dictionary?如何将 ConcurrentDictionary 转换为 Dictionary?
【发布时间】:2011-05-18 20:36:28
【问题描述】:

我有一个 ConcurrentDictionary 对象,我想将它设置为 Dictionary 对象。

不允许在它们之间进行投射。那我该怎么做呢?

【问题讨论】:

    标签: c# .net dictionary concurrentdictionary


    【解决方案1】:

    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 =&gt; kvp.Key, kvp =&gt; kvp.Value, dict.Comparer);
    • 请注意,MSDN 表示这可能不是线程安全的。你如何让它线程安全?
    • 别担心,由于 ConcurrentDictionary,它实际上是线程安全的。您将获得 ConcurrentDictionary 内容的快照。不过,您从中获得的字典稍后本身不会是线程安全的。
    • @Falanwe:它是安全的,但你没有得到内容的快照:“从字典返回的枚举器可以安全地与字典的读取和写入同时使用,但是它并不代表字典的即时快照。通过枚举器公开的内容可能包含调用 GetEnumerator 后对字典所做的修改。”(来自 Remarks msdn.microsoft.com/en-us/library/dd287131.aspx的部分)
    【解决方案2】:

    为什么需要将其转换为字典? ConcurrentDictionary&lt;K, V&gt; 实现了IDictionary&lt;K, V&gt; 接口,这还不够吗?

    如果你真的需要Dictionary&lt;K, V&gt;,你可以复制使用 LINQ:

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

    请注意,这是一个副本。您不能只是将 ConcurrentDictionary 分配给 Dictionary,因为 ConcurrentDictionary 不是 Dictionary 的子类型。这就是像 IDictionary 这样的接口的全部意义:您可以从具体实现(并发/非并发 hashmap)中抽象出所需的接口(“某种字典”)。

    【讨论】:

      【解决方案3】:

      我想我已经找到了一种方法。

      ConcurrentDictionary<int, int> concDict= new ConcurrentDictionary<int, int>( );
      Dictionary dict= new Dictionary<int, int>( concDict);
      

      【讨论】:

        【解决方案4】:
        ConcurrentDictionary<int, string> cd = new ConcurrentDictionary<int, string>();
        Dictionary<int,string> d = cd.ToDictionary(pair => pair.Key, pair => pair.Value);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-19
          • 2013-05-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-06
          • 1970-01-01
          相关资源
          最近更新 更多