views:

577

answers:

3

Hi,

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?

+2  A: 

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.

Neil Whitaker
Cheers, this work for SortedList only though. Is there a way to do it for SortedDictionary?
Grzenio
+5  A: 

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)

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.

Godeke
A: 

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.

Eyal