This tip demonstrates how to sort a user-defined collection class. Let us say we have a custom class as ClientCollection (collection of Client object) which Inherits System.Collections.CollectionBase. To sort the collection , order by LAST NAME , we can use the following steps.
First create a class that implements [IComparer] interface and define the [Compare] method.Following is the class that we will use for sorting Clients order by last name.
[VB.NET CODE STARTS]
Public Class ClientComparer Implements IComparer Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare Dim objClientX As Client = CType(x, Client) ' Client is the class having FirtsName, LastName as properties Dim objClientY As Client = CType(y, Client) Dim sX As String = UCase(objClientX.LastName) ' comparision is made using the LAST NAME OF CLIENT Dim sY As String = UCase(objClientY.LastName) If sX = sY Then Return 0 End If If sX.Length > sY.Length Then sX = sX.Substring(0, sY.Length) If sX = sY Then Return 1 End If ElseIf sX.Length < sY.Length Then sY = sY.Substring(0, sX.Length) If sX = sY Then Return -1 End If End If For i As Integer = 0 To sX.Length If Not sX.Substring(i, 1) = sY.Substring(i, 1) Then Return Asc(CType(sX.Substring(i, 1), Char)) - Asc(CType(sY.Substring(i, 1), Char)) End If Next End Function End Class
[VB.NET CODE ENDS]
Next create a new method in the collection class as follows.
[VB.NET CODE STARTS]
Public Sub SortCollection() InnerList.Sort(New ClientComparer()) ' Innerlist :Gets an System.Collections.ArrayList containing the list of elements in the System.Collections.CollectionBase instance. ' ClientComparer() : takes 2 client object at a time and sort them using last name End Sub
[VB.NET CODE ENDS]
For sorting the client collection we just need to call the SortCollection() method.