Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexed retrieval SortedDictionary<>

Tags:

c#

I read here that SortedDictionary does not allow indexed retrieval unlike SortedList. Then how can I get the nameAddr["C"] correctly in the following code snippet?

        SortedDictionary<string, string> nameAddr = new SortedDictionary<string, string>();
        nameAddr.Add("X", "29");
        nameAddr.Add("A", "30");
        nameAddr.Add("C", "44");           

        Console.WriteLine(nameAddr["C"]);
like image 355
Sunder Avatar asked Sep 15 '09 14:09

Sunder


People also ask

What is SortedDictionary in C#?

In C#, SortedDictionary is a generic collection which is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System. Collection. Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according to the need.

What is the difference between SortedList and SortedDictionary in C#?

A SortedSet is a collection that is maintained in sorted order. A SortedList is a collection that lets you retrieve the keys and/or values using indexes. A SortedDictionary lacks indexes but offers faster insertion and removal of unsorted data than a SortedList.

Is SortedDictionary faster than dictionary?

Dictionary is faster than SortedDictionary because it is implemented as a hash-table, an algorithm that is designed to use excess memory in order to use as few operations as possible.


2 Answers

That's indexing by key. SortedList allows indexing by "index of key", e.g. nameAddr.Values[1] would return "44".

(The collection doesn't allow indexing of name/value pair, just of each of Keys and Values separately.)

For example:

var list = new SortedList<string, string>
{
    { "X", "29" },
    { "A", "30" },
    { "C", "44" },
};

Console.WriteLine(list.Keys[1]); // Prints "C"
Console.WriteLine(list.Values[1]); // Prints "44"
like image 198
Jon Skeet Avatar answered Sep 20 '22 12:09

Jon Skeet


SortedList internally uses an array as the data structure for storage and then just sorts the array as needed to keep the items in order. Since it uses an array the items can be accessed using a numeric index like you would for any array.

SortedDictionary internally uses a red-black binary search tree to keep the items in order. The concept is completely different. There is no array and no analog for retrieving the items by a numeric index. Your only option is to use the key portion of the key-value pair that was added to the dictionary.

With that said. Your code looks correct to me. That is the only way to retrieve items from the dictionary (other than using than Values collection, but that will not give you the numeric indexing ability either).

like image 26
Brian Gideon Avatar answered Sep 21 '22 12:09

Brian Gideon