Sort an array of collections.....

New to Gambas? Post your questions here. No question is too silly or too simple.
Post Reply
ocoquet
Posts: 36
Joined: Friday 18th December 2020 7:56am

Sort an array of collections.....

Post by ocoquet »

let's imagine this collection :

Code: Select all

    Dim tmp_col As Collection[] = New Collection[]
    
    tmp_col.Add([
       "name": "toto4",
       "test": "quattre"
    ])
        tmp_col.Add([
       "name": "toto6",
       "test": "six"
    ])
        tmp_col.Add([
       "name": "toto1",
       "test": "un"
    ])
        tmp_col.Add([
       "name": "toto3",
       "test": "trois"
    ])
    
Write the function like this :

Code: Select all

Public Function ColSort(col As Collection[], ColKey As String, trie As Integer) As Collection[]  
   Dim tmp_col As Collection[] = New Collection[col.count]
   Dim tmp_ar As String[] = New String[]
   
   For i As Integer = 0 To col.count - 1
      tmp_ar.Add(col[i][Colkey] & " (" & i & ")")
   Next
   
   tmp_ar.Sort(trie)   
   For i = 0 To tmp_ar.count - 1
      tmp_col[i] = col[CInt(Split(tmp_ar[i], " ()", "", True)[1])]
   Next
   Return tmp_col
End
And we call the function like this :

Code: Select all

 tmp_col = ColSort(tmp_col, "name", gb.Ascent)
Et voila, Enumerate collections in the array and they are sorted by name!
Olivier
Olivier Coquet
Gambas Dev
Le Forum développeur Gambas
ocoquet
Posts: 36
Joined: Friday 18th December 2020 7:56am

Re: Sort an array of collections.....

Post by ocoquet »

Sorry for the convenience, bbcode del [] in the original message, the code is now, correct.

Olivier
Olivier Coquet
Gambas Dev
Le Forum développeur Gambas
Post Reply