哈希表和关键订单

Phi*_*hil 29 sorting powershell hashtable powershell-2.0

有没有办法在添加哈希表时保持键的顺序?像推/弹机制一样.

例:

$hashtable = @{}

$hashtable.Add("Switzerland", "Bern")
$hashtable.Add("Spain", "Madrid")
$hashtable.Add("Italy", "Rome")
$hashtable.Add("Germany", "Berlin")
$hashtable
Run Code Online (Sandbox Code Playgroud)

我想保留我将元素添加到哈希表的顺序.

Loï*_*HEL 46

PowerShell V1/V2中没有内置解决方案.您将需要使用.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
Run Code Online (Sandbox Code Playgroud)

在PowerShell V3中,您可以转换为[ordered]:

PS> [ordered]@{"Switzerland"="Bern"; "Spain"="Madrid"; "Italy"="Rome"; "Germany"="Berlin"}

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您想[将有序哈希传递给函数](/sf/ask/2979826461/),您还必须使用此类型(`System.Collections.Specialized.OrderedDictionary`)作为参数)。您不能使用“[ordered][hash]”快捷方式作为参数输入,而必须使用完整类型。您可以作为“[hash]”参数传递,但会丢失顺序(因为它作为不太具体的扩展“hash”类型传递;更多信息请参见[该链接](/sf/ask/2979826461/ 1028230)),这可能是不可取的。 (2认同)

Fro*_* F. 10

您可以使用有序字典:

像这样:

$list = New-Object System.Collections.Specialized.OrderedDictionary
$list.Add("Switzerland", "Bern")
$list.Add("Spain", "Madrid")
$list.Add("Italy", "Rome")
$list.Add("Germany", "Berlin")
$list
Run Code Online (Sandbox Code Playgroud)


Jua*_*bío 6

您可以在添加元素时指定一个顺序键:

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

然后,您可以获得按键排序的元素:

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