Alex Guerin
Alex Guerin

Reputation: 2386

VB.NET: order dictionary alphabetically

I have a Dictinary(Of String, Item) and I'm trying to sort it into alphabetical order by the item name. I don't want to use a sorted dictinary and without it, I've having zero luck. Linq is not my strong point...

Public Class Item
    Public Property name As String
    Public Property size As String
    Public Property price As Decimal
    Public Property timeMachine As Boolean
End Class

Upvotes: 1

Views: 1056

Answers (2)

Anax
Anax

Reputation: 9372

(1) Get the list of keys, (2) sort the keys and (3) fetch dictionary's values according to the sorted keys

Dim keys As List(Of String) = dictionary.Keys.ToList
keys.Sort()

For Each str As String In Keys
  Console.WriteLine("{0} -> {1}", str, dictionary.Item(str))
Next

Upvotes: 0

JaredPar
JaredPar

Reputation: 754665

A Dictionary(Of TKey, TValue) is inherently an unordered type. There is no way to sort one. Try using SortedDictionary(Of TKey, TValue) instead.

Dim map = new SortedDictionary(Of String, Item)()

Upvotes: 4

Related Questions