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

Charlie Ogier charlie at cogier.com
Sun Jan 9 18:38:46 CET 2022


Hi Bruce,

My thought was to rebuild the Collection. That way you could not put in 
the one you want to change and add the one you do. The code below will 
change 'th' to "BUSYDAY".

Public Sub Form_Open()

   Dim cAbbr2Weekday As Collection = ["mo": "Monday", "tu": "Tuesday", 
"we": "Wednesday", "th": "Thursday", "fr": "Friday", "sa": "Saturday", 
"su": "Sunday"]
   Dim sName As String
   Dim cCopy As New Collection
   Dim sChange As String = "th"
   Dim sNew As String[] = ["Thursday", "BUSYDAY"]

   For Each sName In cAbbr2Weekday
     If cAbbr2Weekday.Key = sChange Then
       cCopy.Add(sNew[0], snew[1])
     Else
       cCopy.Add(sName, cAbbr2Weekday.Key)
     Endif
   Next

   For Each sName In cCopy
     Print cCopy.Key & " --> " & sName
   Next

End

Output: -
mo --> Monday
tu --> Tuesday
we --> Wednesday
BUSYDAY --> Thursday
fr --> Friday
sa --> Saturday
su --> Sunday

All the best,

Charlie

On 09/01/2022 13:54, Bruce Steers wrote:
> 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
>
>
> ----[http://gambaswiki.org/wiki/doc/netiquette  ]----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.gambas-basic.org/pipermail/user/attachments/20220109/862506eb/attachment.htm>


More information about the User mailing list