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"]);
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.
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.
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.
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"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With