B4J Question Custom type list sorting with multiple criteria

giggetto71

Active Member
Licensed User
Longtime User
Hi,
I have a custom type made of several fields: some are bool, some int. I know I can use "Sorttype" but that allows to specify one field to sort. To make it simple imagine a list of objects made by one int and one bool. What could be a way to sort all the objects with the bool field set to true and then by the int value?
Thanks
 

behnam_tr

Active Member
Licensed User
Longtime User
Hi,
I have a custom type made of several fields: some are bool, some int. I know I can use "Sorttype" but that allows to specify one field to sort. To make it simple imagine a list of objects made by one int and one bool. What could be a way to sort all the objects with the bool field set to true and then by the int value?
Thanks

you can save bool as an integer.
0 = false
1=true

Type MyType (Name As String, bool As Int)

and now you can sorttype("bool ",true)
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
you can save bool as an integer.
0 = false
1=true

Type MyType (Name As String, bool As Int)

and now you can sorttype("bool ",true)
I'm sorry but I don't think that's the question, boolean vs int; it's if you can sort a list of custom type objects on "field1" AND THEN on "field2" (AND THEN on "field3"...).

I don't think it's possible; you can (should) use an SQLite db and table and a query with the ORDER BY clause.
 
Last edited:
Upvote 0

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
To make it simple imagine a list of objects made by one int and one bool. What could be a way to sort all the objects with the bool field set to true and then by the int value?
why dont create another field where you write the other fields f0f25 if you order by this field, you will get the sorting you need.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can sort by multiple fields by sorting the list multiple times, starting with the inner field and going up.

Example:
B4X:
Type Test(FieldA As Int, FieldB As Int, FieldC As Int)

Dim List As List
List.Initialize
For i = 1 To 100
    List.Add(CreateTest(Rnd(1, 5), Rnd(1, 5), Rnd(1, 5)))
Next
List.SortType("FieldC", True)
List.SortType("FieldB", True)
List.SortType("FieldA", True)
For Each t As Test In List
    Log($"${t.FieldA} -> ${t.FieldB} -> ${t.FieldC}"$)
Next
It works because the sort algorithm is stable. This means that items with the same value preserve the order.
It will work in B4A and B4J. It also seems to work in B4i though in the current version it cannot be guaranteed. It will be in the next one.
 
Upvote 0
Top