Wish Add Ascending and Descending to B4XComparatorSort

b4x-de

Active Member
Licensed User
Longtime User
Currently, B4XComparatorSort seems to sort only in ascending or descending order, depending on the implementation of compare() in the custom Comparator class. If you need both sort orders, you need two separate classes or you need to reverse the order of the resulting list.

Could you please consider adding a boolean property to B4XComparatorSort that can be used to easily switch from ascending to descending sort without implementing a separate Comparator class or reversing the order of the result?

Thank you,
Thomas
 

b4x-de

Active Member
Licensed User
Longtime User
Thank you very much! I had missed that I am passing an object and not the class to B4XComparatorSort. The object can of course be instantiated and configured appropriately before it is used for comparison. I have extended the example from the original post to allow ascending and descending sorting with a checkbox. Just in case it might be helpful for someone. Here's what the adapted PersonComparator class looks like now:

Adapted PersonComparator Class:
Sub Class_Globals
    Private mintDesc As Int
End Sub

Public Sub Initialize
    mintDesc = 1
End Sub

'Return a positive number if o1 greater than o2 (=o1 comes after o2), 0 if o1 equals to o2 and a negative number if o1 smaller than o2.
Public Sub Compare (pObj1 As Object, pObj2 As Object) As Int
    Dim pers1 As Person = pObj1
    Dim pers2 As Person = pObj2
    Dim intResult As Int
  
    If pers1.Status = "Employee" And pers2.Status <> "Employee" Then
        intResult = -1
    Else If pers2.Status = "Employee" And pers1.Status <> "Employee" Then
        intResult = 1
    Else If pers1.Name = pers2.Name Then
        If pers1.Age > pers2.Age Then
            intResult = 1
        Else If pers1.Age < pers2.Age Then
            intResult = -1
        Else
            intResult = 0
        End If
    Else
        intResult = pers1.Name.CompareTo(pers2.Name)
    End If
  
    Return intResult * mintDesc
End Sub

Public Sub setDesc(pbolDesc As Boolean)
    If pbolDesc Then
        mintDesc = -1
    Else
        mintDesc = 1
    End If
End Sub
 

Attachments

  • B4XComparatorSortAscDesc.zip
    27.1 KB · Views: 52
Top