[Gambas-user] Rename a Collection Key retaining the order

Bruce Steers bsteers4 at gmail.com
Sun Jan 9 14:54:28 CET 2022


Is there a simple way to rename a collection key name but retain the order?

I found i can rename it using Swap but it pops the item at the and of the
collection index.

Best i have so far is this fuction that copies and returns the collection
with a preserved order.
so if my second collection item had the key "t2" I can do this...

























*cCollection = RenameKey(cCollection, "t2", "ttt2")Public Sub RenameKey(c
As Collection, sName As String, sNewName As String) As Collection    Dim i
As Integer = c.Keys.Find(sName)  ' find key position  Swap c[sName],
c[sNewName]  ' swap key names  ' make a new collection preserving original
order  Dim nc As New Collection  For cnt As Integer = 0 To c.Count - 1
If cnt = i Then  ' insert point so move last added key to our position
nc.Add(c[c.Keys[c.Keys.Max]], c.Keys[c.Keys.Max])    Else If cnt > i Then
 'after insert so shunt keys back one      nc.Add(c[c.Keys[cnt - 1]],
c.Keys[cnt - 1])    Else  ' before insert so just copy
nc.Add(c[c.Keys[cnt]], c.Keys[cnt])    Endif  Next  Return nc  End*

Am i missing a one line command or is that the only way to do it ?

Cheers all :)
BruceS
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20220109/47fc2d6e/attachment.htm>


More information about the User mailing list