Thursday, April 18, 2024 03:13

Table of contents >> Data Structures > Sorted Dictionary

Sorted Dictionary

Sorted Dictionary is just a normal Dictionary data structure, but with its keys sorted. Of course, it is obvious that having its elements sorted will make this data structure slightly slower than a normal Dictionary, but it does offer the advantage of making an in memory sorted lookup very easy.

To better understand how a Sorted Dictionary works, let’s create a code where we will add a few elements in random order, and then we will lookup some of the keys:

The output code will look like this:

In the code above, we used the TryGetValue() method, which spared us of using another instruction, bu first checking if the key exists, and then assigning its value to the v variable, when this element was found. Finally, we used a foreach loop to iterate through the elements of the sorted dictionary.

Be aware that the performance of Sorted Dictionary degrades rapidly when we start adding a lot of elements.

Note that there is also a SortedList collection in the System.Collections.Generic namespace. This provides essentially the same functionality as the SortedDictionary but with a different internal implementation. The SortedList has different performance characteristics, particularly when inserting or removing elements from the collection.

Tags: ,

Leave a Reply



Follow the white rabbit