[Gambas-user] A piece of code to sort an array of collections

Olivier Coquet ocoquet at 3d-phenomen.fr
Tue Jan 19 18:18:49 CET 2021


A little piece of code for anyone wondering how to sort a collection 
table on one of its keys.
example:

dim macollection as collection[] = new collection[]

macollection.add([
"clef1": "nimporte quoi",
"clef5": "nimporte quoi aussi"
])

macollection.add([
"clef1": "1er test",
"clef5": "zzzzz"
])

This array of collections has two elements (collections) each composed 
of two keys (key1 and key5)
If they are listed, they will be in the order above.
Let's use this code:


Public Function ColSort(col As Collection[], ColKey As String, trie As 
Integer) As Collection[] 'Trie d'un tableau de collection sur la clef 
demandée
Dim tmp_col As Collection[] = New Collection[col.count] 'un tableau de 
collection temporaire pour les manips
Dim tmp_ar As String[] = New String[] 'un tableau de chaînes pour les manips

For i As Integer = 0 To col.count - 1 'on parcoure les collections et on 
récupère
tmp_ar.Add(col/[Colkey] & Chr(26) & i) 'La valeur de clef et le numéro 
d'ordre original
Next

tmp_ar.Sort(trie) 'on trie le tableau obtenu
For i = 0 To tmp_ar.count - 1 'on parcour le tableau trié
tmp_col/= col[CInt(Split(tmp_ar/, Chr(26), "", True)[1])] 'on 
ré-attribue chaque collection dans le bon ordre
Next
Return tmp_col'on retourne le tableau de collection trié
End///

/////////We call the function like this:///


//////macollection=ColSort(macollection, "clef1", gb.Ascent)//////

//////And we get an array of collections sorted on the key "clef1", in 
ascending order. Note that the function will work for any key provided, 
as long as it exists in the collections.

Magic!
Friendship
Olivier
//////

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20210119/84cccc7f/attachment.htm>


More information about the User mailing list