|
|
Title | Sort objects by making a class implement the IComparable interface |
Description | This example shows how to make a series of color samples in Visual Basic .NET. |
Keywords | compare, IComparable, sort, sortable, Array.Sort, VB.NET |
Categories | Algorithms, Software Engineering, VB.NET |
|
|
The CustomerInfo class implements the IComparable interface. This requires that it provide a CompareTo method that returns -1, 0, or 1 if the current object should be ordered less than, equal to, or greater than another object. This exmaple sorts on the objects' ID fields.
|
|
Private Class CustomerInfo
Implements IComparable
Public Name As String
Public ID As Integer ' We sort on this value.
Public Sub New(ByVal new_name As String, ByVal new_id _
As Integer)
Name = new_name
ID = new_id
End Sub
Public Overrides Function ToString() As String
Return ID.ToString() & ". " & Name
End Function
' Compare to another CustomerInfo for sorting.
Public Function CompareTo(ByVal obj As Object) As _
Integer Implements System.IComparable.CompareTo
Dim other As CustomerInfo = DirectCast(obj, _
CustomerInfo)
Return Me.ID.CompareTo(other.ID)
End Function
End Class
|
|
When the program starts, the form's Load event handler creates an array containing several CustomerInfo items. It then calls Array.Sort to sort the array. Array.Sort uses the class's CompareTo method to figue out how to sort the items.
|
|
Private Sub Form1_Load(...) Handles MyBase.Load
' Make some data.
Dim items(9) As CustomerInfo
items(0) = New CustomerInfo("Archer", 4)
items(1) = New CustomerInfo("Beck", 7)
items(2) = New CustomerInfo("Cantu", 2)
items(3) = New CustomerInfo("Deevers", 1)
items(4) = New CustomerInfo("Edwards", 9)
items(5) = New CustomerInfo("Finnagan", 3)
items(6) = New CustomerInfo("Guy", 5)
items(7) = New CustomerInfo("Hennesey", 8)
items(8) = New CustomerInfo("Irving", 6)
items(9) = New CustomerInfo("Jacquinth", 4)
'' Uncomment to test duplicate objects.
'items(6) = New CustomerInfo("Finnagan", 3)
'items(7) = New CustomerInfo("Edwards", 9)
'items(8) = New CustomerInfo("Finnagan", 3)
'items(9) = New CustomerInfo("Deevers", 1)
' Sort the items
Array.Sort(items)
' Display the results.
lstItems.Items.Clear()
For i As Integer = 0 To items.Length - 1
lstItems.Items.Add(items(i).ToString())
Next i
End Sub
|
|
|
|
|
|