1

i was searching for a simple solution that i can use in sorting a dictionary by value, and i was not content with what i found, so i made up these two functions for sorting a dictionary ascending and descending. I do not assume that they are perfect, so improvements are welcomed. They are written in VB.Net and use an intermediary dictionary.

 Public Function SortDictionaryAsc(ByVal dict As Dictionary(Of Long, Decimal)) As Dictionary(Of Long, Decimal)
    Dim final As New Dictionary(Of Long, Decimal)
    Dim min As Decimal = dict.Values.ToList.Max
    Dim key As Long
    Do
        min = dict.Values.Max + 1
        For Each x In dict.Keys
            If dict(x) < min Then
                min = dict(x)
                key = x
            End If
        Next
        final.Add(key, min)
        dict.Remove(key)
    Loop While dict.Keys.Count > 0
    Return final
End Function

Public Function SortDictionaryDesc(ByVal dict As Dictionary(Of Long, Decimal)) As Dictionary(Of Long, Decimal)
    Dim final As New Dictionary(Of Long, Decimal)
    Dim max As Decimal = 0
    Dim prev As Decimal = 0
    Dim key As Long
    Do While dict.Keys.Count - 1 > 0
        For Each x In dict.Keys
            If dict(x) > max Then
                max = dict(x)
                key = x
            End If
        Next
        final.Add(key, max)
        dict.Remove(key)
        max = 0
    Loop
    Return final
End Function
catalin ilie
  • 121
  • 2
  • 7

2 Answers2

3

It's better use LINQ for that. Look at example

    ' Create an array of Pet objects.
    Dim pets() As Pet = {New Pet With {.Name = "Barley", .Age = 8}, _
                         New Pet With {.Name = "Boots", .Age = 4}, _
                         New Pet With {.Name = "Whiskers", .Age = 1}}

    ' Order the Pet objects by their Age property.
    Dim query As IEnumerable(Of Pet) = _
        pets.OrderBy(Function(pet) pet.Age)

More details on MSDN

Dima Pasko
  • 1,170
  • 12
  • 20
0

For best performance you can use LINQ to object http://msdn.microsoft.com/it-it/library/bb397919.aspx

An example of sorting, using one of your function and sorting by key is:

Public Function SortDictionaryAsc(ByVal dict As Dictionary(Of Long, Decimal)) As     Dictionary(Of Long, Decimal)       
    Dim final = From key In dict.Keys Order By key Ascending Select key
End Sub
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111