Put this class in your solution. Change ‘[object name of your collection]’ to be the name of your object that defines your collection.
Public Class SimpleComparer
Implements IComparer(Of [object name of your collection])
Private _propertyToSort As String
Private _sortOrder As System.Windows.Forms.SortOrder = System.Windows.Forms.SortOrder.Ascending
Public Sub New(ByVal propertyToSort As String, ByVal sortOrder As System.Windows.Forms.SortOrder)
MyBase.new()
_sortOrder = sortOrder
_propertyToSort = propertyToSort
End Sub
Public Property SortOrder() As System.Windows.Forms.SortOrder
Get
Return _sortOrder
End Get
Set(ByVal Value As System.Windows.Forms.SortOrder)
_sortOrder = Value
End Set
End Property
Public Property PropertyToSort() As String
Get
Return _propertyToSort
End Get
Set(ByVal Value As String)
_propertyToSort = Value
End Set
End Property
Public Function Compare(ByVal x As[object name of your collection], ByVal y As [object name of your collection]) As Integer Implements System.Collections.Generic.IComparer(Of[object name of your collection]).Compare
Dim prop As Reflection.PropertyInfo = x.GetType.GetProperty(Me.PropertyToSort)
If Me.SortOrder = System.Windows.Forms.SortOrder.None OrElse prop.GetValue(x, Nothing) = _
prop.GetValue(y, Nothing) Then
Return 0
Else
If prop.GetValue(x, Nothing) > prop.GetValue(y, Nothing) Then
If Me.SortOrder = System.Windows.Forms.SortOrder.Ascending Then
Return 1
Else
Return -1
End If
Else
If Me.SortOrder = System.Windows.Forms.SortOrder.Ascending Then
Return -1
Else
Return 1
End If
End If
End If
End Function
End Class
Call your IComparer class with your collection as follows. Replace [property of your object within the collection to sort on] with the property name to sort. You can also choose Ascending or Descending to sort by.
[your collection].Sort(New SimpleComparer(“[property of your object within the collection to sort on]”, System.Windows.Forms.SortOrder.Ascending))