1

我有一个对象列表,用于存储我所做的提要搜索的搜索结果。在添加到列表时,我给对象一个结果相关性的分数,以便我可以将这些结果推到顶部。

我的对象实现了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
4

2 回答 2

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
于 2012-07-20T11:54:39.120 回答
0

除了汉斯在评论中所说的(你需要实现通用接口!),代码有两点让我畏缩:

  1. 使用DirectCast而不是CType. 后者是一个通用的演员表,不能很好地展示这里实际做了什么。DirectCast只允许某些强制转换发生,特别是没有转换。在这里很合适,因为您不转换。

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

    Return Score.CompareTo(OtherItem.Score)
    
于 2012-07-20T11:56:09.747 回答