【问题标题】:When would you use a List<KeyValuePair<T1, T2>> instead of a Dictionary<T1, T2>?什么时候使用 List<KeyValuePair<T1, T2>> 而不是 Dictionary<T1, T2>?
【发布时间】:2010-12-18 15:36:18
【问题描述】:

相同类型的 KeyValuePair List 和 Dictionary 有什么区别?是否有合适的时间使用其中一种?

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    当您不需要快速查找键时 - 维护 Dictionary 使用的哈希表有一定的开销。

    【讨论】:

    • 另外列表插入操作比字典中的快
    • 它的字段是只读的,但你可以随时替换列表中的整个元素。
    • 更多差异here
    【解决方案2】:

    简而言之,列表不会强制键的唯一性,因此如果您需要该语义,那么您应该使用它。

    【讨论】:

    • +1 请注意,字典也不强制值的唯一性!
    【解决方案3】:

    字典是包含键值对集合的通用类型。字典对于查找操作来说很快,因为它在内部使用散列函数。这意味着,所有键在字典中都必须是唯一的

    考虑以下示例:

    List<KeyValuePair<int, string>> pairs = new List<KeyValuePair<int, string>>();
    pairs.Add(new KeyValuePair<int, string>(1, "Miroslav"));
    pairs.Add(new KeyValuePair<int, string>(2, "Naomi"));
    pairs.Add(new KeyValuePair<int, string>(2, "Ingrid"));
    
    Dictionary<int, string> dict = new Dictionary<int, string>();
    dict.Add(1, "Miroslav");
    dict.Add(2, "Naomi");
    dict.Add(2, "Ingrid"); // System.ArgumentException: An item with the same key has already been added.
    

    所以你应该始终考虑两个至少两件事:

    1. 您要在字典中搜索具体项目吗?
    2. 你想要一些字段吗 非唯一(例如对:名/姓)。

    【讨论】:

    • 我认为这里的重点是字典键必须是唯一的,而 List 键不能是唯一的。
    • @BrunoBieri List可能不是唯一的
    • 我纠正了你 2 年前的评论,你注意到了。难怪 SO 是唯一值得信赖和最受欢迎的问答平台。
    【解决方案4】:

    当您关心项目的顺序时,列表也会很有用。

    【讨论】:

    • SortedDictionary 不会报道这个吗?
    • 是的,但是 SortedDictionary 不能覆盖值的顺序,只能覆盖键。
    【解决方案5】:

    除了 Phillip Ngan 的回答,SOAP 或其他,您不能 XML 序列化实现 IDictionary 的对象。

    问:为什么我不能序列化哈希表?

    答:XmlSerializer 无法处理实现 IDictionary 接口的类。这部分是由于进度限制,部分是由于哈希表在 XSD 类型系统中没有对应的事实。唯一的解决方案是实现一个不实现 IDictionary 接口的自定义哈希表。

    from here

    【讨论】:

      【解决方案6】:

      在 Silverlight 的 SOAP Web 服务中,我们发现 Dictionary 不会序列化。在这种情况下,您将在字典上使用 KeyValuePair 列表。

      .

      【讨论】:

        【解决方案7】:

        来自http://blogs.msdn.com/bclteam/archive/2004/09/03/225473.aspx

        KeyValuePairDictionaryEntry
        [Krzysztof Cwalina]

        我们讨论了一个问题 执行IEnumerable on Dictionary&lt;K,V&gt;。应该是什么类型 IEnumerable.GetEnumerator().Current 返回? KeyValuePair&lt;K,V&gt;DictionaryEntry?相同的 ICollection.CopyTo。什么的实例 类型应该复制到数组中吗?

        我们决定如下:IEnumerableICollection 接口 实现将使用 KeyValuePair&lt;K,V&gt; 作为项目类型。 IDictionary特定成员 (GetEnumerator返回 IDictionaryEnumerator) 将使用 DictionaryEntry 作为项目类型。

        原因是我们在一个过程中 在哪里做出改变 IEnumerator&lt;T&gt; 将扩展 IEnumerator。会很奇怪 如果从层次结构中走 Dictionary&lt;K,V&gt;->IEnumerable&lt;T&gt;->IEnumerable 我们突然改变了类型 从枚举器返回的项目。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-25
          • 2014-08-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-09
          相关资源
          最近更新 更多