Here's a very general way to sort properties without having to implement multiple sorting sorters for each slightly different view.
it will allow any number of Columns sortings (although you need to do a bit more to support different sorting directions)
The disadvantage is obviously not the most effective, although using calling delegates is much more efficient than using reflection. You also need to define the general function of the properties of objects that you can sort. By making this a more specific object, you can fix this aspect ...
Public Class PropertySortComparer Implements IComparer Public Delegate Function GetProp(ByVal obj As Object) As Object Public SortProps As New List(Of GetProp) Public Sub New(ParamArray SortMethods() As GetProp) Me.SortProps.AddRange(SortMethods) End Sub Public Function Compare(x As Object, y As Object) As Integer Implements System.Collections.IComparer.Compare For Each gp As GetProp In SortProps Dim xVal As Object = gp.Invoke(x) Dim yVal As Object = gp.Invoke(y) If xVal > yVal Then Return 1 ElseIf xVal < yVal Then Return -1 Else 'next loop does next property End If Next Return 0 End Function End Class Public Module module1 Sub test() Dim buffer As New List(Of Rectangle) buffer.Add(New Rectangle(34, 55, 40, 30)) buffer.Add(New Rectangle(34, 55, 45, 38)) buffer.Add(New Rectangle(34, 56, 46, 30)) buffer.Add(New Rectangle(34, 70, 45, 30)) Dim Lst() As Rectangle = buffer.ToArray Array.Sort(Lst, New PropertySortComparer(AddressOf Left, AddressOf Top, AddressOf Widht)) 'Lst is now sorted by Left, Top, Width End Sub Public Function Left(r As Object) As Object Return r.Left End Function Public Function Top(r As Object) As Object Return r.Top End Function Public Function Widht(r As Object) As Object Return r.Width End Function End Module
source share