Indexed Search SortedDictionary <>

I read here that SortedDictionary does not allow indexed extraction unlike SortedList. Then how can I get 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"]); 
+4
source share
2 answers

This is key indexing. SortedList allows you to index the "key index", for example. nameAddr.Values[1] will return "44".

(The collection does not allow indexing a name / value pair only for each of Keys and Values separately.)

For instance:

 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" 
+5
source

SortedList internally uses the array as the data structure to store, and then simply sorts the array as needed to keep the elements in order. Since it uses an array, elements can be accessed using a numerical index, as with any array.

SortedDictionary internally uses a red black binary data tree to keep items in order. The concept is completely different. There is no array and there is no analogue for extracting elements using a numerical index. Your only option is to use the key part of the key-value pair that has been added to the dictionary.

That said. Your code looks right to me. This is the only way to retrieve items from a dictionary (other than using the Values ​​collection, but it will also not give you a numerical indexing ability).

+5
source

All Articles