IComparable没有正确排序对象

时间:2012-07-20 11:28:01

标签: .net vb.net list object

我有一个对象列表,用于存储我所做的Feed搜索的搜索结果。在添加到列表时,我会给对象一个关于结果相关程度的分数,以便我可以将这些结果推到最顶层。

我的对象实现了IComparable接口并且具有compareto函数并且所有编译都正确但是当我对列表进行排序时(list.sort())这似乎对结果没有任何影响(更高)得分项目不在最底层)

有人可以告诉我做错了吗?

Public Class SearchFeedItem
    Implements IComparable

    Private _score As Integer = 0

    Public Property Score() As Integer
        Get
            Return _score
        End Get
        Set(ByVal value As Integer)
            _score = value
        End Set
    End Property

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
        Dim OtherItem As SearchFeedItem = CType(obj, SearchFeedItem)

        If Me.Score < OtherItem.Score Then
            Return 1
        End If

        If Me.Score > OtherItem.Score Then
            Return -1
        Else
            Return 0
        End If
    End Function

End Class

2 个答案:

答案 0 :(得分:1)

如果您希望底部得分较高的项目,则应为

 Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo

    If obj Is Nothing Then Return 1
    If Me.Score > DirectCast(obj, SortableObject).Score Then Return 1
    If Me.Score < DirectCast(obj, SortableObject).Score Then Return -1

    Return 0

    End Function

以下是实现IComparable的对象的快速示例,该对象从低到高进行排序。

Module Module1

    Sub Main()
        Dim sortableObjects = New List(Of SortableObject) From
                               {New SortableObject With {.Score = 12},
                               New SortableObject With {.Score = 5},
                               New SortableObject With {.Score = 120},
                               New SortableObject With {.Score = 99}}

        sortableObjects.Sort() // 5, 9, 99, 120
    End Sub
End Module

Public Class SortableObject : Implements IComparable
    Public Property Score As Integer

    Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo

    If obj Is Nothing Then Return 1
    If Me.Score > DirectCast(obj, SortableObject).Score Then Return 1
    If Me.Score < DirectCast(obj, SortableObject).Score Then Return -1

    Return 0
    // Edit: Or as Konrad mentioned,  Return (Me.Score.CompareTo(DirectCast(obj, SortableObject).Score)). This sorts the items in ascending order.

    End Function
End Class

答案 1 :(得分:0)

除了Hans在评论中所说的内容(你需要实现通用接口!),有两个关于代码的事情让我感到畏缩:

  1. 使用DirectCast代替CType。后者是一个通用的演员,并没有很好地表明这里实际做了什么。 DirectCast只允许某些演员阵容发生,特别是没有转换。这是适当的,因为你不转换。

  2. 整个CompareTo方法可以缩短为一行:

    Return Score.CompareTo(OtherItem.Score)