Hello my fellow Daniwebers!

I am having some problems wrapping my head around the task sorting a List(Of CustomType)

I have a list containing a custom class.
The class contains Two DateTime objects, Start and End.

I am trying to sort the list descending so that the shortest timespan will be on the bottom of the list.
I am unsure how to write the function that returns the value to sort.

I have read Microsoft's documentation here and, as all ways, I am more confused after reading it than I was before I began.

This is what I have deducted from the article:

lstType.Sort(Address SortMyList)



Private Function SortMyList(ByVal x As Type, Byval y As Type) As Type
    Try
        Dim tsX As TimeSpan = x.dEnd.Subtract(x.dStart)
        Dim tsY As TimeSpan = y.dEnd.Subtract(y.dStart)

        If tsX > tsY Then
            Return x
        Else
            Return y
        End If
    Catch ex As Exception
        MsgBox("Exception from:" & ex.Source & vbcrlf & ex.Message & vbcrlf & ex.StackTrace.ToString)
        'Used just to break execution
        Throw New NullReferenceException("")
    End Try
End Function

Would this logic be correct?

Recommended Answers

The comparison delegate returns an integer denoting the relation between the two objects: 0 for equal, -1 if x is "smaller", and +1 if x is "larger". So it would be more like this:

Private Function SortMyList(ByVal x As MyType, ByVal y As MyType) As Integer
    Dim tsX As TimeSpan …
Jump to Post

All 2 Replies

The comparison delegate returns an integer denoting the relation between the two objects: 0 for equal, -1 if x is "smaller", and +1 if x is "larger". So it would be more like this:

Private Function SortMyList(ByVal x As MyType, ByVal y As MyType) As Integer
    Dim tsX As TimeSpan = x.dEnd.Subtract(x.dStart)
    Dim tsY As TimeSpan = y.dEnd.Subtract(y.dStart)

    If tsX < tsY Then
        Return -1
    ElseIf tsX > tsY Then
        Return 1
    Else
        Return 0
    End If
End Function

Assuming this is how you want to compare the timespans, of course.

commented: Thanks Deceptikon! +6

Ah, I understand now.

I think what threw me for a loop was the fact that they returned the retval (which is still an integer)

Thanks for the help!