C# 从 SortedList 或 SortedDictionary 中获取第 i 个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/234181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting i-th value from a SortedList or SortedDictionary
提问by Grzenio
I have a sorted collection of objects (it can be either SortedList or SortedDictionary, I will use it mainly for reading so add performance is not that important). How can I get the i-th value?
我有一个排序的对象集合(它可以是 SortedList 或 SortedDictionary,我将主要将它用于阅读,因此添加性能不是那么重要)。我怎样才能得到第 i 个值?
So e.g. when I have numbers 1, 2, 3, 4, 5 in the collection and I want the median (so 3 in this example), how can I do it?
因此,例如,当我在集合中有数字 1、2、3、4、5 并且我想要中位数(在本例中为 3)时,我该怎么做?
采纳答案by Neil
Try something like this:
尝试这样的事情:
list.Values[list.Count / 2];
list.Values[list.Count / 2];
Note that a true median would average the two numbers in the middle if Count is even.
请注意,如果 Count 为偶数,则真正的中位数将平均中间的两个数字。
回答by Godeke
You can use code like
您可以使用类似的代码
list.Values[index]
for a sorted list.
对于排序列表。
The easiest way with a SortedDictonary would be to use the ElementAt() method:
SortedDictonary 最简单的方法是使用 ElementAt() 方法:
dict.ElementAt(index).Value
However, this is slower than in the list case.
但是,这比列表情况要慢。
In either case, you need to check your count. If it is odd, take index = (list.length-1) / 2 ). If it is even, take index1 = list.length/2 AND index2 = list.length/2 - 1 and average the values.
无论哪种情况,您都需要检查您的计数。如果是奇数,取 index = (list.length-1) / 2 )。如果是偶数,取 index1 = list.length/2 AND index2 = list.length/2 - 1 并取平均值。
回答by Eyal
If you need to get an element by index in a SortedDictionary many times, the performance is miserable. Make a new SortedList with the SortedDictionary as input and access the SortedList. Runs many, many times faster.
如果需要多次通过SortedDictionary中的索引获取一个元素,性能就惨不忍睹了。使用 SortedDictionary 作为输入创建一个新的 SortedList 并访问 SortedList。运行速度快很多倍。
回答by mudrak patel
You can extract value at a particular position by using the below syntax:
您可以使用以下语法在特定位置提取值:
sortedDictionaryName.ElementAt(index);
If you want extract key or value of an element at a desired index:
如果要在所需索引处提取元素的键或值:
sortedDictionaryName.ElementAt(index).Key //For only Key
sortedDictionaryName.ElementAt(index).Value //For only Value