Went to sort a dictionary today and found that MyDictionary.Sort wasn't there.

Heres a method to sort a dictionary by value.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'Non sorted Dictionary
    Dim Dictionary As New Dictionary(Of Integer, String)
    Dictionary.Add(1, "Greg")
    Dictionary.Add(2, "Marsha")
    Dictionary.Add(3, "Peter")
    Dictionary.Add(4, "Jan")
    Dictionary.Add(5, "Bobby")
    Dictionary.Add(6, "Cindy")
    'Sorted Dictionary
    Dictionary = SortDictionary(Dictionary)

End Sub

Private Function SortDictionary(ByVal dictionaryToSort As Dictionary(Of Integer, String)) As Dictionary(Of Integer, String)

    'Create a List to do the sorting and
    'pass the dictionaryToSort to it as 
    'a list.
    Dim SortList As List(Of KeyValuePair(Of Integer, String))
    SortList = dictionaryToSort.ToList


    'Now sort the list by value with the custom
    'Icomparer class.
    SortList.Sort(New DictionaryValueComparer)

    'Finally return the list as a dictionary of integer and string.
    'The first function is the key selector. The second is the value
    'The dictionary passed in is now sorted by value.
    Return SortList.ToDictionary(Of Integer, String)(Function(keyPair As KeyValuePair(Of Integer, String)) keyPair.Key, _
                                                         Function(valuePair As KeyValuePair(Of Integer, String)) valuePair.Value)

End Function

Private Class DictionaryValueComparer
   Implements IComparer(Of KeyValuePair(Of Integer, String))
   'Simple class that inherits the IComparer of Type.
   'Just compare the values.
   Public Function Compare(ByVal x As System.Collections.Generic.KeyValuePair(Of Integer, String), ByVal y As System.Collections.Generic.KeyValuePair(Of Integer, String)) As Integer Implements System.Collections.Generic.IComparer(Of System.Collections.Generic.KeyValuePair(Of Integer, String)).Compare
         Return String.Compare(x.Value, y.Value)
   End Function
End Class
5 Years
Discussion Span
Last Post by Unhnd_Exception

That's fine but the result by me is the following: 1,1,1,10,11,12,123,124,19,2,21,22,23,29,3, ..... ideal of course if I get this 1,2,3,10,11,12,19,21,22,23,29…
how can I am solve this.


SortedDictionary Sorts by Key not Value and is the point of the snippet. The above sorting is wrong because your sorting numeric values by string. You need to change the String.Compare to something that will work with numeric. You will need to make your own class that implements Icomparer to do your sorting.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.