如何按.NET 2.0中的值对SortedDictionary进行排序?

时间:2015-03-11 09:34:28

标签: vb.net linq sorting .net-2.0 sorteddictionary

我有一个SortedDictionary:

Dim myFilterItems As SortedDictionary(Of String, FilterItem)
myFilterItems = New SortedDictionary(Of String, FilterItem)(StringComparer.CurrentCultureIgnoreCase)

FilterItem类的定义如下:

Private Class FilterItem
    Public ValueToSort As Object
    Public IsChecked As Boolean
    Public IsAbsent As Boolean = False
End Class

我需要枚举按FilterItem.ValueToSort属性排序的SortedDictionary。使用LINQ,它很容易 - 我们得到相应的IEnumerable,然后使用For Each:

Dim mySortedValueList As IEnumerable(Of KeyValuePair(Of String, FilterItem))
mySortedValueList = From entry In myFilterItems Order By entry.Value.ValueToSort Ascending
For Each entry As KeyValuePair(Of String, FilterItem) In mySortedValueList
    ' ...
Next

如何在.NET 2.0中有效地做到这一点?

1 个答案:

答案 0 :(得分:0)

我使用列表重写了我的代码,正如Jon Skeet建议的那样。从我的测试中可以看出,我的性能与LINQ查询相同 - 甚至可以获得5-10%的增益。新版本的代码如下所示:

Dim mySortedValueList As New List(Of KeyValuePair(Of String, FilterItem))(myFilterItems)
If iArr <> iGAFMValueType.Text Then
    mySortedValueList.Sort(AddressOf CompareFilterItemsByValuesToSort)
End If

Private Shared Function CompareFilterItemsByValuesToSort(ByVal itemX As KeyValuePair(Of String, FilterItem), ByVal itemY As KeyValuePair(Of String, FilterItem)) As Integer
    Dim myValueX As IComparable = TryCast(itemX.Value.ValueToSort, IComparable)
    Dim myValueY As IComparable = TryCast(itemY.Value.ValueToSort, IComparable)
    If (myValueX Is Nothing) Then
        If (myValueY Is Nothing) Then
            Return 0
        End If
        Return -1
    End If
    If (myValueY Is Nothing) Then
        Return 1
    End If

    Dim myTypeX As Type = myValueX.GetType()
    Dim myTypeY As Type = myValueY.GetType()
    If (myTypeX <> myTypeY) Then
        Return String.CompareOrdinal(myTypeX.Name, myTypeY.Name)
    End If

    Return myValueX.CompareTo(myValueY)
End Function

然而,在处理这种比较算法时,我发现我无法比较某些数字类型的值 - 尽管可以比较它们(例如,SByte和Double值)。顺便说一句,在这种情况下,原始的LINQ查询也失败了。但这是另一个在这个问题中继续存在的故事:

How to compare two numeric values (SByte, Double) stored as Objects in .NET 2.0?