Problema: išrikiuoti Dictionary objektą.
Sprendimas:
1. Inicializuoti pradinius duomenis
Dim Dictionary As New Dictionary(Of String, Integer)
Dictionary.Add("A", 1)
Dictionary.Add("B", 8)
Dictionary.Add("C", 7)
Dictionary.Add("D", 4)
Dictionary.Add("E", 78)
Dictionary.Add("F", 0)
Dictionary.Add("G", 1)
Dictionary.Add("H", 0)
Dictionary.Add("I", 7)
Dictionary.Add("J", 12)
Dictionary.Add("K", 41)
Dictionary.Add("L", 6)
2. Išrikiuoti
Dictionary = SortDictionary(Dictionary)
3. Įgyvendinti SortDictionary funkciją
Private Function SortDictionary(ByVal dictionaryToSort As Dictionary(Of String, Integer)) As Dictionary(Of String, Integer)
Dim SortList As List(Of KeyValuePair(Of String, Integer))
SortList = dictionaryToSort.ToList
dictionaryToSort.Clear()
SortList.Sort(New DictionaryValueComparer)
Return SortList.ToDictionary(Of String, Integer)(Function(keyPair As KeyValuePair(Of String, Integer)) keyPair.Key, Function(valuePair As KeyValuePair(Of String, Integer)) valuePair.Value)
End Function
Private Class DictionaryValueComparer
Implements IComparer(Of KeyValuePair(Of String, Integer))
Public Function Compare(ByVal x As System.Collections.Generic.KeyValuePair(Of String, Integer), ByVal y As System.Collections.Generic.KeyValuePair(Of String, Integer)) As Integer Implements System.Collections.Generic.IComparer(Of System.Collections.Generic.KeyValuePair(Of String, Integer)).Compare
Dim num1 As Integer = x.Value
Dim num2 As Integer = y.Value
If num1 < num2 Then
Return 1
End If
If num1 > num2 Then
Return -1
End If
Return 0
End Function
End Class
Rezultatai:
http://stackoverflow.com/questions/2671236/sorting-a-dictionary-by-value - išrikiuoja skaičius
http://www.daniweb.com/software-development/vbnet/code/361733/sort-a-dictionary - išrikiuoja String eilutes
Komentarų nėra:
Rašyti komentarą