Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 377
Grzenio Avatar asked Oct 24 '08 16:10

Grzenio


People also ask

When should you use a SortedDictionary T class rather than a SortedList T class?

SortedDictionary is implemented with Binary Search Tree, while SortedList is implemented with two internal arrays for keys and values, respectively. SortedList is more memory-efficient than SortedDictionary, and SortedList is faster than SortedDictionary when it needs to go through all items at once.

When should I use SortedList?

If you need to access items using an index or populate sorted data all at once in the collection, you might use a SortedList. If minimizing memory overhead is important and you need more lookups and fewer insert and delete operations, you might opt for a SortedList.

In what way SortedList will add the values?

The SortedList<int, string> will store keys of int type and values of string type. The Add() method is used to add a single key-value pair in a SortedList . Keys cannot be null or duplicate. If found, it will throw a run-time exception.

What is SortedList?

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable. The collection of items is always sorted by the key value.


2 Answers

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.

like image 140
Godeke Avatar answered Sep 26 '22 00:09

Godeke


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.

like image 20
Neil Avatar answered Sep 26 '22 00:09

Neil