Grzenio
Grzenio

Reputation: 36689

Getting i-th value from a 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 add performance is not that important). How can I get the i-th value?

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?

Upvotes: 23

Views: 23509

Answers (4)

Godeke
Godeke

Reputation: 16281

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:

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.

Upvotes: 34

mudrak patel
mudrak patel

Reputation: 605

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

Upvotes: 6

Eyal
Eyal

Reputation: 5848

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.

Upvotes: 3

Neil
Neil

Reputation: 7437

Try something like this:

list.Values[list.Count / 2];

Note that a true median would average the two numbers in the middle if Count is even.

Upvotes: 9

Related Questions