VB.NET Sort Method for a Collection Class
Posted by malakablog on August 4, 2009
I have a VB.NET collection class EmployeesCollection for an Employee Class that got an Integer Property named Age; I want to create a method (SortByAge) to sort the collection members by Age.
This is the EmployeesCollection Class:
Imports Microsoft.VisualBasic
Public Class EmployeesCollection
Inherits System.Collections.CollectionBase
Public Sub Add(ByVal tblEmployee As Employee)
' Invokes Add method of the List object to add a widget.
List.Add(tblEmployee)
End Sub
Public ReadOnly Property Item(ByVal index As Integer) As Employee
Get
' The appropriate item is retrieved from the List object and
' explicitly cast to the Widget type, then returned to the
' caller.
Return CType(List.Item(index), Employee)
End Get
End Property
End Class
To create the SortByAge method I need a SortHelper Class, This helper Class will include a Function called Compare to compare between the Age values of the employees, the SortHelper Class will be part of the EmployeesCollection Class.
Private Class AgeSortHelper
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
If x.Age > y. Age Then
Return 1
End If
If x. Age < y. Age Then
Return -1
End If
Return 0
End Function
End Class
Now we need to create the SortByAge method for the EmployeesCollection Class, in this method we will use the AgeSortHelper to sort the Employees.
Public Sub SortByAge()
Dim sorter As System.Collections.IComparer = New AgeSortHelper()
InnerList.Sort(sorter)
End Sub
This is the Final EmployeesCollection Class:
Imports Microsoft.VisualBasic
Public Class EmployeesCollection
Inherits System.Collections.CollectionBase
Public Sub Add(ByVal tblEmployee As Employee)
' Invokes Add method of the List object to add a widget.
List.Add(tblEmployee)
End Sub
Public ReadOnly Property Item(ByVal index As Integer) As Employee
Get
' The appropriate item is retrieved from the List object and
' explicitly cast to the Widget type, then returned to the
' caller.
Return CType(List.Item(index), Employee)
End Get
End Property
Public Sub SortByAge()
Dim sorter As System.Collections.IComparer = New AgeSortHelper()
InnerList.Sort(sorter)
End Sub
Private Class AgeSortHelper
Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
If x.Age > y. Age Then
Return 1
End If
If x. Age < y. Age Then
Return -1
End If
Return 0
End Function
End Class
End Class
This entry was posted on August 4, 2009 at 4:48 pm and is filed under Uncategorized. Tagged: application, beginner, code, Collection, development, list, Programming, sort, VB.NET, VS2005. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.






