Sort a list containg types

Ricky D

Well-Known Member
Licensed User
Longtime User
I am using B4A 1.8

I have types like

B4X:
Type typeAddMenuItem(Id As Int, MenuItem As String)
Dim AddMenuItems As List

I have a list of items like this.

How do I sort based on MenuItem?

1.8 doesn't have SortType - it just has a sort which is only good for single item lists.

regards, Ricky
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
There is no simple way to do it without List.SortType that was introduced in v1.9.

If MenuItem is unique then you can use another Map and List to implement it.
Create a Map with MenuItem as the key and the custom type as value. Add the keys to the second List. Sort the list. Go over the items in the list and take the values from the Map.
The values will be now sorted.
 
Upvote 0

Ricky D

Well-Known Member
Licensed User
Longtime User
Thanks Erel.

But I'm not sure what the code should look like? Any ideas?

regards, Ricky
 
Upvote 0

Ricky D

Well-Known Member
Licensed User
Longtime User
B4X:
Sub sort(obj As Object) As List 
   If obj Is typeAddMenuItem Then
      Dim m As Map
      m.Initialize
      Dim list2 As List
      list2.Initialize
      
      For i=0 To AddMenuItems.Size-1
         Dim a As typeAddMenuItem 
         a = AddMenuItems.Get(i)
         m.Put(a.MenuItem, a)
      Next
      
      For i=0 To m.Size-1
         list2.Add(m.GetKeyAt(i))
      Next
      list2.Sort(True)
      
      AddMenuItems.Clear 
      For i=0 To m.Size-1
         Dim s As String
         s = list2.Get(i)
         Dim a As typeAddMenuItem 
         a = m.Get(s)
         AddMenuItems.Add(a)
      Next 
                  Return AddMenuItems
   End If
End Sub

this works nicely. Thanks for the tips Erel.

regards, Ricky
 
Last edited:
Upvote 0
Top