从SortedList或SortedDictionary获取第i个值

Grz*_*nio 15 .net c# collections

我有一个排序的对象集合(它可以是SortedList或SortedDictionary,我将主要用于阅读,所以添加性能并不重要).我怎样才能获得第i个值?

所以例如,当我在集合中有数字1,2,3,4,5并且我想要中位数(在这个例子中为3)时,我该怎么办呢?

God*_*eke 24

你可以使用像这样的代码

list.Values[index] 
Run Code Online (Sandbox Code Playgroud)

对于排序列表.

使用SortedDictonary的最简单方法是使用ElementAt()方法:

dict.ElementAt(index).Value
Run Code Online (Sandbox Code Playgroud)

但是,这比列表情况要慢.

在任何一种情况下,您都需要检查您的计数.如果是奇数,则取index =(list.length-1)/ 2).如果是偶数,则取index1 = list.length/2 AND index2 = list.length/2 - 1并取值.


Nei*_*eil 8

尝试这样的事情:

list.Values [list.Count/2];

请注意,如果Count为偶数,则真正的中位数将平均中间的两个数字.

  • 干杯,这仅适用于SortedList。有没有办法对SortedDictionary执行此操作? (2认同)

mud*_*tel 5

您可以使用以下语法在特定位置提取值:

sortedDictionaryName.ElementAt(index);
Run Code Online (Sandbox Code Playgroud)

如果要在所需索引处提取元素的键或值:

sortedDictionaryName.ElementAt(index).Key //For only Key
sortedDictionaryName.ElementAt(index).Value //For only Value
Run Code Online (Sandbox Code Playgroud)