按值对字典排序

时间:2011-12-01 11:43:00

标签: vb.net sorting dictionary

我正在寻找一个简单的解决方案,我可以用它按值排序字典,我不满足于我发现的东西,所以我编写了这两个函数来排序字典升序和降序。我不认为它们是完美的,所以欢迎改进。它们是用VB.Net编写的,并使用中间词典。

 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

2 个答案:

答案 0 :(得分:3)

最好使用LINQ。 看一下例子

    ' 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

答案 1 :(得分:0)

为获得最佳性能,您可以使用LINQ来对象http://msdn.microsoft.com/it-it/library/bb397919.aspx

使用您的某个功能和按键排序的排序示例是:

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