Sometimes you’re going to need a data structure that is an array of classes and you’re going to want to sort them. The standard array Sort method can only sort simple types (Text, Integer, etc), so what do you do?
The traditional technique has been to use SortWith. You create a separate array of a simple type, populate it and then sort the temporary array using SortWith to sort the class array.
But there is an even slicker way to sort that was added in 2015 Release 3. You can now create your own custom comparison method and use that to sort the class. This custom method returns 0 if the values to compare are equal, a positive if the first value is greater than the second, and a negative value if the first value is less than the second.
This code can sort an array of Xojo.Core.Date:
Function DateCompare(value1 As Xojo.Core.Date, value2 As Xojo.Core.Date) As Integer ' This assumes the array is populated with non-Nil dates If value1.SecondsFrom1970 > value2.SecondsFrom1970 Then Return 1 If value1.SecondsFrom1970 < value2.SecondsFrom1970 Then Return -1 Return 0 End Function myDates.Sort(AddressOf DateCompare)
To learn more about class array sorting, refer to these doc topics:
- Array Sort Method in Reference Guide
- Array SortWith Method in Reference Guide
- Sorting Class Arrays in User Guide
Looking for more tips?