Link Round-Up for 10/18/07Site News for 10/14/07 through 10/20/07

Introduction to the Comparer Delegate

October 19th, 2007

The Comparer Delegate Does the Hard Work for You

Once you have data in a generic List or Dictionary you may find that you need to sort it into the order you need. This is fairly easy if you’re using simple data types since .NET provides default comparers but it can get a little trickier if you need to sort objects. In this article we’ll look at how to use Comparer Delegates to do this.

What is a Comparer Delegate?

A comparer delegate is a routine that is used to compare two objects. It returns a 1 if the value of the first object is greater, -1 if the value of the first object is lesser, and 0 if the objects are equal. Since we’re working with objects we can compare multiple values in the two objects to determine which is greater than the other.

Code Example #1

In this example we’ll look at sorting PointF coordinates by their distance from 0,0. First, let’s load up our list and call the Sort method with our comparer that we’ll write in a moment.

Dim CoordinateList As New List(Of PointF)(New PointF() {New PointF(14, 22), New PointF(17, 21), _
                                          New PointF(15, 8), New PointF(15, 20), _
                                          New PointF(16, 7), New PointF(15, 21), _
                                          New PointF(17, 7), New PointF(16, 21), _
                                          New PointF(14, 23)})
CoordinateList.Sort(AddressOf ComparePointF)

Now, let’s code our comparer routine, ComparePointF:

Public Function ComparePointF(ByVal positionOne As PointF, ByVal positionTwo As PointF) As Integer
    Dim DistanceOne As Double = Math.Sqrt((positionOne.X ^ 2) + (positionOne.Y ^ 2))
    Dim DistanceTwo As Double = Math.Sqrt((positionTwo.X ^ 2) + (positionTwo.Y ^ 2))
    If DistanceOne > DistanceTwo Then
        Return 1
    ElseIf DistanceOne < DistanceTwo Then
        Return -1
    Else
        Return 0
    End If
End Function

Here we’re using the Pythagorean distance formula to determine the distance from 0,0 for each point and then comparing the results. The List object handles all of the sorting internally so the performance is quite good.

Code Example #2

In this example, we have an invoice object where we’re wanting to sort the objects first by customer type and then by the total amount of the invoice. Here’s what our comparer delegate would look like:

Public Function CompareInvoices(ByVal invoiceOne As Invoice, ByVal invoiceTwo As Invoice) As Integer
    If invoiceOne.CustomerType > invoiceTwo.CustomerType Then
        Return 1
    ElseIf invoiceOne.CustomerType < invoiceTwo.CustomerType Then
        Return -1
    Else
        If invoiceOne.Total > invoiceTwo.Total Then
            Return 1
        ElseIf invoiceOne.Total < invoiceTwo.Total Then
            Return -1
        Else
            Return 0
        End If
    End If
End Function

As you can see in this function, we first compare the customer type, then the total amount. Of course, you could make this even more complex for your sorting situations. All you have to keep in mind is your integer return value.

I hope these examples have been helpful to you in learning how to use the comparer delegate. If you have any further questions or observations about this subject, please feel free to leave a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: VB.NET Tutorials


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives