Home
VB.NET
Sort Dictionary
This page was last reviewed on 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.
Shows a dictionary
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.Shows a dictionary
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 11, 2021 (edit link).
Home
Changes
© 2007-2024 Sam Allen.