Tuesday, January 13, 2004

After the previous sorting of strings using the iCompare.  It’s also possible to sort objects.

 

To do this we just have to add 2 extra lines in the code, and change a few parameters :

 

Code :

Public Class PersonComparerName

    Implements IComparer

 

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare

        Dim xEntity As person = x

        Dim yEntity As person = y

 

        If xEntity.Name = yEntity.Name Then

            Return 0

        ElseIf xEntity.Name < yEntity.Name Then

            Return -1

        Else

            Return 1

        End If

    End Function

End Class

 

As you can see, we can now use the properties of the object person to sort on.

 

Result :

We can even go a little further, by sorting on two properties of our class  In this case we have to add an extra sorting check.

 

Code :

Public Class PersonComparerCityName

    Implements IComparer

 

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare

        Dim xEntity As person = x

        Dim yEntity As person = y

 

        If xEntity.City = yEntity.City Then

            If xEntity.Name = yEntity.Name Then

                Return 0

            ElseIf xEntity.Name < yEntity.Name Then

                Return -1

            Else

                Return 1

            End If

        ElseIf xEntity.City < yEntity.City Then

            Return -1

        Else

            Return 1

        End If

    End Function

End Class

 

In this code, first we sort on city.  When the city is equal, then we will check also the name to sort on.

 

Result :

 

1/13/2004 12:04:11 PM (Romance Standard Time, UTC+01:00)  #     | 
Tracked by:
"weight loss drug rimonabant" (weight loss drug rimonabant) [Trackback]