Hello I have an ArrayList full of Person objects. I would like to sort
the object array by the objects property 'Name' so when I loop through
it and populate a combobox they are in order. How do I attack
something like this? Any help is greatly appreciated.
thanks!
Make the person class implement the IComparable interface, Write code
for the Compare method that appears. Then it will all magically work
when you call the sort method. If this is a 2005 version then you can
use IComparable(Of Person). And use a list(Of Person) instead of
arraylist too!
If you have 2003, then change this to plain IComparable. The parameter
of the Compare method will be an object, so cast it to Person.
Public Class Person
Implements IComparable(Of Person)
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
' called by the arraylist.sort method.
Public Function CompareTo(ByVal other As Person) As Integer _
Implements System.IComparable(Of Person).CompareTo
' Compare this ones name with the other ones name.
' return <0 if this one comes first,
' 0 if they are equal,
' >0 if the other one comes first.
' String.Compare does this anyway
Return String.Compare(Me.Name, other.Name)
End Function
End Class