Background:
Collections like SortedList and SortedDictionary appeared in .NET for the convenient storage of key-value pairs in a sorted manner by key. They are used when fast key-based access is important while maintaining sorting.
Problem:
Frequent errors are related to the incorrect choice between these collections, using incompatible key types (without IComparable support), and incorrect expectations regarding behavior when inserting duplicate keys.
Solution:
In Visual Basic, the classes SortedList(Of TKey, TValue) and SortedDictionary(Of TKey, TValue) are used for storing sorted data.
Code example:
Dim sortedList As New SortedList(Of String, Integer)() sortedList.Add("Alex", 27) sortedList.Add("Mike", 34) Dim age As Integer = sortedList("Alex") ' 27 Dim sortedDict As New SortedDictionary(Of Integer, String)() sortedDict.Add(3, "Three") sortedDict.Add(1, "One") For Each pair In sortedDict Console.WriteLine(pair.Key & ": " & pair.Value) Next
Key Features:
1. Can keys of existing elements in SortedList or SortedDictionary be changed?
No, it's not possible to change the key of an existing element. To "change" a key, you must remove the original pair and add a new one with the adjusted key.
2. What exception occurs when attempting to add an already existing key?
An ArgumentException is thrown.
Dim sl As New SortedList(Of Integer, String)() sl.Add(1, "One") sl.Add(1, "Repeat") ' ArgumentException
3. What happens if keys use a type that does not implement IComparable?
The compiler will allow the creation of the collection, but attempting to add the first element will throw an InvalidOperationException.
Class MyObj End Class Dim sd As New SortedDictionary(Of MyObj, String)() sd.Add(New MyObj(), "test") ' Exception
Implemented a user registry by identifier (userId – key) and age (value) using SortedList. The key was chosen as a custom object type (User) that does not implement IComparable. Unexpected exceptions arise when adding users.
Pros:
Cons:
Using SortedDictionary(Of Integer, User), where the key is a simple Integer type (userId), which supports comparison. Everything works correctly, and sorting by user identifiers is in place.
Pros:
Cons: