Home
VB.NET
Sort Dictionary
Updated Dec 11, 2021
Dot Net Perls
Sort Dictionary. A Dictionary cannot be sorted—but its keys can be arranged. We can loop over the string keys in alphabetical order.
Sorting details. 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.
Dictionary
Sort
Input and output. 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
Example. 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.
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
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 Module
apple = 1 car = 2 zebra = 0
Sort method used. In .NET, the Sort method on the List type is implemented with a Quick Sort algorithm. This means it is efficient on strings.
A summary. 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.
ToList
Final notes. The collections you can obtain from the Dictionary (such as List) can be sorted. With these resulting types, we can perform many conversions.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 11, 2021 (edit link).
Home
Changes
© 2007-2025 Sam Allen