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
dictionaryToSort.Clear()
'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
'selector.
'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