Sort
Dictionary
A Dictionary
cannot be sorted—but its keys can be arranged. We can loop over the string
keys in alphabetical order.
Some steps are involved in sorting a Dictionary
. We obtain the Keys
and sort them—and then loop over that. Values from the Dictionary
can still be accessed.
Consider a VB.NET Dictionary
that contains string
keys, and integer values. When sorted, we want the keys to be alphabetical.
car 2 zebra 0 apple 1 SORTED: apple 1 car 2 zebra 0
Let us look at a VB.NET program that adds key and value pairs to a Dictionary
. Then, we acquire the list of strings, using the ToList
extension method on the Keys
property.
Sort
instance method on the keys collection. It requires no argument.for-each
loop construct to loop over the List
collection, and do lookups for all values.Module Module1 Sub Main() ' Create Dictionary with string keys. Dim dict As New Dictionary(Of String, Integer) dict.Add("car", 2) dict.Add("zebra", 0) dict.Add("apple", 1) ' Get list of keys. Dim keys As List(Of String) = dict.Keys.ToList ' Sort the keys. keys.Sort() ' Loop over the sorted keys. For Each str As String In keys Console.WriteLine("{0} = {1}", str, dict.Item(str)) Next End Sub End Moduleapple = 1 car = 2 zebra = 0
Sort
method usedIn .NET, the Sort
method on the List
type is implemented with a Quick Sort
algorithm. This means it is efficient on strings.
We sorted the keys in a Dictionary
using the Keys
property. We then used the ToList
and Sort
methods to manipulate the elements. Dictionaries themselves cannot be reordered.
The collections you can obtain from the Dictionary
(such as List
) can be sorted. With these resulting types, we can perform many conversions.