【发布时间】: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