IComparable

J

John Devlon

Hi,

Could somebody please tell me how to use Icomparable in a .NET project? Like
I was a 5 year old?

I'm trying to sort an array of objects and I can't get it to work .... How
do I modify the main class using IComparable ? How do I sort the array in
practice?

Example...

I would like to sort the array first using the zipcode, second the Lastname
and finally the age ...


Public Class Person
Private vName as String
Private vLastName as String
Private vZipcode as Integer
Private vAge as Integer

Public property Name as String
Get
Return vName
End get
Set(ByVal value As String)
vName=value
end set
end property

Public property LastName as String
Get
Return vLastName
End get
Set(ByVal value As String)
vLastName=value
end set
end property

Public property Zipcode as Integer
Get
Return vZipcode
End get
Set(ByVal value As Integer)
vZipcode=value
end set
end property

Public property Age as Integer
Get
Return vAge
End get
Set(ByVal value As Integer)
vAge=value
end set
end property

End Class



Many, many thanks

John
 
G

Guest

John,

Your Person class would implement the generic version of IComparable like
this:

Public Class Person
Implements IComparable(Of Person)

Your Person class then needs to implement IComparable's CompareTo method:

Public Function CompareTo(ByVal person As Person) As Integer Implements
System.IComparable(Of Person).CompareTo

If Me.Zipcode = person.Zipcode Then
If Me.LastName = person.LastName Then
Return Me.Age.CompareTo(person.Age)
Else
Return Me.LastName.CompareTo(person.LastName)
End If
Else
Return Me.Zipcode.CompareTo(person.Zipcode)
End If

End Function

Now all you need to do is add objects of type Person to an array (or an
arraylist or a List (Of Person)) and then call the array's Sort method.

Kerry Moorman
 
J

John Devlon

Hi Kerry,

Many Many Thanks... Your the best ... you saved my life ...

How can I repay you ?

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top