Hashtables and key order

后端 未结 7 1051
青春惊慌失措
青春惊慌失措 2020-12-05 17:46

Is there a way to keep the order of keys in a hashtable as they were added? Like a push/pop mechanism.

Example:

$hashtable = @{}

$hashtable.Add(\"Sw         


        
7条回答
  •  爱一瞬间的悲伤
    2020-12-05 17:56

    You can give one sequential key as you add elements:

    $hashtable = @{}
    $hashtable[$hashtable.count] = @("Switzerland", "Bern")
    $hashtable[$hashtable.count] = @("Spain", "Madrid")
    $hashtable[$hashtable.count] = @("Italy", "Rome")
    $hashtable[$hashtable.count] = @("Germany", "Berlin")
    $hashtable
    

    Then, you can get elements sorted by the key:

    echo "`nHashtable keeping the order as they were added"
    foreach($item in $hashtable.getEnumerator() | Sort Key)
    {
        $item
    }
    

提交回复
热议问题