Sorting a generic List(Of T) using IComparable(Of T)

List(Of T) supports sorting through it’s Sort method.  When you call Sort it will use the default comparer for the items it contans.  So if you have a custom class in there, you need to implement IComparable or IComparable(Of T). 

Here is some code that shows how to do this.  This code sorts lowest to highest.

    Public Function CompareTo(ByVal other As CustomClass) As Integer Implements System.IComparable(Of CustomClass).CompareTo
Dim myscore As Integer = Me.SomeValue
Dim otherscore As Integer = other.SomeValue
If myscore > otherscore Then
Return 1
ElseIf myscore = otherscore Then
Return 0
Else
Return -1
End If
End Function
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s