2012-07-20 114 views
1

我有一個對象列表,它存儲了我所做的源搜索的搜索結果。在添加到列表中時,我會爲該對象提供有關結果相關性的評分,以便我可以將這些結果推到頂部。IComparable沒有正確排序對象

我的對象實現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 
+0

我已經實現如上述,但仍不能正確排序,新的代碼:公共功能的CompareTo(BYVAL其他作爲SearchFeedItem)作爲整數器具System.IComparable(OF SearchFeedItem).CompareTo 如果Me.Score other.Score然後 返回-1 Else Return 0 End If End Function – 2012-07-20 11:55:04

回答

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 
0

除了什麼漢斯在評論(!您需要實現通用接口),也有對碼兩件事情說這讓我畏縮:

  1. 使用DirectCast代替CType 。後者是一個通用的演員,並不能很好地顯示這裏實際做了什麼。 DirectCast只允許某些演員發生,特別是沒有轉換。這是適當的,因爲你不轉換。

  2. 整個CompareTo方法可以縮短到一個單一的線:

    Return Score.CompareTo(OtherItem.Score)