0

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?

2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by Begginnerdev
1

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.

Edited by deceptikon

Votes + Comments
Thanks Deceptikon!
0

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!

Edited by Begginnerdev

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.