当Array.Sort调用x.CompareTo(x)时,IComparer没有返回零

时间:2011-04-04 17:38:46

标签: .net asp.net sorting icomparer

我已经实现了一个IComparer来对搜索页面上的结果进行排序。有时,在生产中,用户会收到此错误。搜索的所有数据(条件,分页,排序)都在查询字符串上,我正在使用ELMAH库,因此我可以在错误的电子邮件报告中看到详细信息。如果我将来自收到错误的用户的查询字符串复制到我的浏览器中,页面工作正常。所以它显然是非确定性的。

这是我的比较者:

Public Class ReverseDateComparer
    Implements IComparer(Of Promotion)

    Public Function Compare(ByVal x As Promotion, ByVal y As Promotion) As Integer Implements System.Collections.Generic.IComparer(Of Promotion).Compare
        If y.ExpirationDate = x.ExpirationDate Then
            Return x.PlainTitle.CompareTo(y.PlainTitle)
        Else
            Return y.ExpirationDate.CompareTo(x.ExpirationDate)
        End If
    End Function
End Class

所以基本上,按到期日期降序排序,然后按标题升序排序。它有什么明显的错误吗?

2 个答案:

答案 0 :(得分:2)

y.ExpirationDate = x.ExpirationDate不太确定。尝试

Public Class ReverseDateComparer
    Implements IComparer(Of Promotion)

    Public Function Compare(x As Promotion, y As Promotion) As Integer
        Dim c As Integer = x.ExpirationDate.CompareTo(y.ExpirationDate)
        If c = 0 Then
            Return x.PlainTitle.CompareTo(y.PlainTitle)
        Else
            Return c
        End If
    End Function
End Class

答案 1 :(得分:0)

如果x是y,你可以简单地返回0。

Public Class ReverseDateComparer
Implements IComparer(Of Promotion)

Public Function Compare(ByVal x As Promotion, ByVal y As Promotion) As Integer Implements System.Collections.Generic.IComparer(Of Promotion).Compare
    If x is y Then
        Return 0
    ElseIf y.ExpirationDate = x.ExpirationDate Then
        Return x.PlainTitle.CompareTo(y.PlainTitle)
    Else
        Return y.ExpirationDate.CompareTo(x.ExpirationDate)
    End If
End Function

结束班