Tip: Simple Comparer for sorting in VB.NET
Here’s a simple routine to sort a collection of objects posted by Jan Tielens.
Dim customers As New ArrayList
Or you can use the Sort
method of the strong typed collection, inheriting from CollectionBase.
customers.Sort(New SimpleComparer("Name"))
or
customers.Sort(New SimpleComparer("Name", SortOrder.Descending))
The complete code for SimpleComparer
class is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Public Class SimpleComparer Implements IComparer
Private _propertyToSort As String
Private _sortOrder As SortOrder
Public Sub New(ByVal propertyToSort As String)
Me.new(propertyToSort, System.Windows.Forms.SortOrder.Ascending)
End Sub
Public Sub New(ByVal propertyToSort As String, ByVal sortOrder As SortOrder)
MyBase.new()
_propertyToSort = propertyToSort
_sortOrder = sortOrder
End Sub
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Dim prop As Reflection.PropertyInfo = x.GetType.GetProperty(Me.PropertyToSort)
If Me.SortOrder = 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
Public Property SortOrder() As SortOrder
Get
Return _sortOrder
End Get
Set(ByVal Value As 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
End Class
This post is licensed under
CC BY 4.0
by the author.