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)
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)
您可以在添加元素时指定一个顺序键:
$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)