Hashtables and key order

后端 未结 7 1018
青春惊慌失措
青春惊慌失措 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 18:14

    There is no built-in solution in PowerShell V1 / V2. You will want to use the .NET System.Collections.Specialized.OrderedDictionary:

    $order = New-Object System.Collections.Specialized.OrderedDictionary
    $order.Add("Switzerland", "Bern")
    $order.Add("Spain", "Madrid")
    $order.Add("Italy", "Rome")
    $order.Add("Germany", "Berlin")
    
    
    PS> $order
    
    Name                           Value
    ----                           -----
    Switzerland                    Bern
    Spain                          Madrid
    Italy                          Rome
    Germany                        Berlin
    

    In PowerShell V3 you can cast to [ordered]:

    PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}
    
    Name                           Value
    ----                           -----
    Switzerland                    Bern
    Spain                          Madrid
    Italy                          Rome
    Germany                        Berlin
    
    0 讨论(0)
提交回复
热议问题