【问题标题】:Setting the i-th value of a SortedDictionary设置 SortedDictionary 的第 i 个值
【发布时间】:2009-09-09 16:38:11
【问题描述】:

我需要在我的 sortedDictionary 中设置一个元素的值,通过索引访问。

sortedDictionary.Values[index] = value; // compile error

请注意,以下是不正确的,因为它是通过键而不是索引访问的。

sortedDictionary[index] = value; // incorrect

我想出了以下解决方案,但直觉告诉我它很慢。我假设按键访问是O(log N),索引访问是O(1),但我不确定。

sortedDictionary[sortedDictionary.ElementAt(index).Key] = value;

一些背景:

我使用 SortedDictionary 是因为我需要快速插入、删除、查找以及能够访问相邻元素。 (即次高或次低。)效率很重要。

【问题讨论】:

  • ElementAt(index) 是可枚举的扩展方法 - 它在 O(n) 时间内工作,因为 SortedDictionary 没有实现 IList 接口。
  • 似乎没有一个内置的 .NET 结构可以满足我的需要。我可以选择跳过列表。

标签: c# .net collections sorteddictionary


【解决方案1】:

这是一种权衡。

您可以使用 SortedList 并获得更快的索引查找,但您会牺牲插入速度。

引用MSDN

...两者之间的另一个区别 SortedDictionary<(Of <(TKey, TValue>)>)SortedList<(Of <(TKey, TValue>)>) 类是 SortedList&lt;(Of &lt;(TKey, TValue&gt;)&gt;) 支持高效的索引检索 键和值通过 键返回的集合和 值属性。没有必要 重新生成列表时 属性被访问,因为 列表只是 键和值的内部数组。

SortedDictionarySortedList 都实现了 IDictionary,所以我会同时获取一些测试数据和代码分析器并尝试两者。

如果两者都不够快,您可能需要开始考虑使用Dictionary(快速插入、更新和键查找)并在第二个数据结构中手动维护索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 2011-09-30
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多