HOW TO: Sort an array using an IComparable

A common problem in .NET is being able to present your data to a user in a way that makes sense to them. One such way is to provide them a list of information that is sorted in a way that is proper to their function. For example, if you were showing a list of transactions, you may want to sort in a descending order based on their date to show the last transaction that happened.

This can be accomplished using an array and/or list and the IComparable. In the object which you are sorting, implement the interface and use any rules necessary to compare two objects. In our previous example, we discussed a transaction. Here is a transaction object which sorts based on the transaction date:

Public Class Transaction
   Implements IComparable
   Private m_TransactionAmount As Decimal
   Private m_TransactionDate As Date
   Public Sub New(ByVal TransactionAmount As Decimal, ByVal TransactionDate As Date)
      m_TransactionAmount = TransactionAmount
      m_TransactionDate = TransactionDate
   End Sub

   Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
      'implements a icomparer rule to allow for sorting based on transaction date, and then transaction type

      Dim dteValueToCompare As Date
      Dim blnCredit As Boolean
      If TypeOf obj Is Transaction Then
         dteValueToCompare = CType(obj, Transaction).TransactionDate
         dteValueToCompare = obj
      End If
      Return Date.Compare(TransactionDate, dteValueToCompare)
   End Function
End Class

Now, to sort the transactions, you can use an Array and use the Array.Sort method to sort them by date. You can also use a Array.Reverse to get a reverse sort in case you want them in descending order. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>