VB.NET Sort Dictionary

Sort the keys in a Dictionary, converting the Keys to a List with ToList.

Sort Dictionary. A Dictionary cannot be sorted. But its keys can be arranged. We can loop over the string keys in alphabetical order. We obtain the Keys and sort them—and then loop over that. Values from the Dictionary can still be accessed.

Example. First, let us look at a VB.NET program that adds five key and value pairs to a Dictionary(Of String, Integer). Then, we acquire the list of strings, using the ToList extension method on the Keys property.

Then: We invoke the Sort instance method on the keys collection. It requires no argument.

Next: We use the for-each loop construct to loop over the List collection, and do lookups for all values.

For Each, For
VB.NET program that sorts string keys in Dictionary Module Module1 Sub Main() ' Create Dictionary with string keys. Dim dict As New Dictionary(Of String, Integer) dict.Add("dog", 0) dict.Add("cat", 1) dict.Add("mouse", 5) dict.Add("eel", 3) dict.Add("programmer", 2) ' Get list of keys. Dim keys As List(Of String) = dict.Keys.ToList ' Sort the keys. keys.Sort() ' Loop over the sorted keys. Dim str As String For Each str In keys Console.WriteLine("{0} -> {1}", str, dict.Item(str)) Next End Sub End Module Output cat -> 1 dog -> 0 eel -> 3 mouse -> 5 programmer -> 2

Sort method used. In the .NET Framework, the Sort method on the List type is implemented with a Quick Sort algorithm, making it very efficient on strings. The string "cat" was added second in the source code.

But: It is ordered first in the alphabetical printout, establishing the program's correctness here.

Summary. We sorted the keys in a VB.NET Dictionary collection using the Keys property. We then used the ToList and Sort methods to manipulate the elements. The Dictionary internals themselves cannot be sorted or reordered.

But: The collections you can obtain from the Dictionary (such as List) can be sorted.

And: This enables a greater degree of opportunity for programmatic conversions. It tends to also make programs more complex.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to