In order to provide sorting capabilities for me Session List custom control, I needed a way to sort the ArrayList that I am using to store my data. Within the .Net Compact Framework it is possible to due this by implementing the IComparable interface on the object class I’m storing in the array. This allows a single sort method. To provide multiple ways to sort the data, I can add more flexibility allowing multiple sort orders by implementing IComparer. The code listed below allows me to easily add the desired sort without adding a lot of custom sort code and taking advantage of the framework.
Public Class SessionListItem
Implements IComparable
.
. ' The rest of the class code is here
.
Public Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo
' The default sort method
Return Me.SessionCode.CompareTo(CType(obj, SessionListItem).SessionCode)
End Function
Public Shared ReadOnly Property SortByName() As IComparer
Get
Return CType(New SortByNameClass, IComparer)
End Get
End Property
Public Shared ReadOnly Property SortByTitle() As IComparer
Get
Return CType(New SortByTitleClass, IComparer)
End Get
End Property
Public Class SortByNameClass
Implements IComparer
Public Function Compare(ByVal obj1 As Object, ByVal obj2 As Object) As Integer Implements IComparer.Compare
'SortByName can use the default IComparable interface
' so call the CompareTo method
Return CType(obj1, IComparable).CompareTo(CType(obj2, SessionListItem))
End Function 'Compare
End Class 'SortByNameClass
Public Class SortByTitleClass
Implements IComparer
Public Function Compare(ByVal obj1 As Object, ByVal obj2 As Object) As Integer Implements IComparer.Compare
'SortByTitle compares the integer property
Dim SessionListItem1 As SessionListItem = CType(obj1, SessionListItem)
Return SessionListItem1.m_SessionTitle.CompareTo(CType(obj2, SessionListItem).m_SessionTitle)
End Function 'Compare
End Class 'SortByTitleClass
End Class