Getting i-th value from SortedList or SortedDictionary

I have a sorted collection of objects (it can be either SortedList or SortedDictionary, I will use it mainly for reading, so adding performance is not so important). How can I get the i-th value?

So, for example, when I have the numbers 1, 2, 3, 4, 5 in the collection and I want the median (so 3 in this example), how can I do this?

+14
collections c #
source share
4 answers

Try something like this:

list.Values ​​[list.Count / 2];

Note that the true median will average two numbers in the middle if the graph is even.

+8
source share

You can use the code as

list.Values[index] 

for a sorted list.

The easiest way to use SortedDictonary is to use the ElementAt () method:

 dict.ElementAt(index).Value 

However, this is slower than with the list.

In any case, you need to check your account. If it's 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.

+23
source share

You can extract the value at a specific position using the following syntax:

 sortedDictionaryName.ElementAt(index); 

If you want to extract the key or value of an element with the desired index:

 sortedDictionaryName.ElementAt(index).Key //For only Key sortedDictionaryName.ElementAt(index).Value //For only Value 
+3
source share

If you need to get an item by index in SortedDictionary many times, performance is unbearable. Create a new SortedList with SortedDictionary as input and access the SortedList. It works many, many times faster.

+1
source share

All Articles