35

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

例子:

$hashtable = @{}

$hashtable.Add("Switzerland", "Bern")
$hashtable.Add("Spain", "Madrid")
$hashtable.Add("Italy", "Rome")
$hashtable.Add("Germany", "Berlin")
$hashtable

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

4

7 回答 7

60

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

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

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

Name                           Value
----                           -----
Switzerland                    Bern
Spain                          Madrid
Italy                          Rome
Germany                        Berlin
于 2013-02-15T09:02:44.743 回答
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
于 2013-02-15T09:01:11.297 回答
6

您可以在添加元素时提供一个顺序键:

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

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

echo "`nHashtable keeping the order as they were added"
foreach($item in $hashtable.getEnumerator() | Sort Key)
{
    $item
}
于 2015-04-10T00:52:22.263 回答
1

PowerShell 1 的方式是添加一个哈希表成员来保留添加顺序。无需使用 System.Collections.Specialized.OrderedDictionary:

$Hash = New-Object PSObject                                       
$Hash | Add-Member -MemberType NoteProperty -Name key1 -Value val1
$Hash | Add-Member -MemberType NoteProperty -Name key2 -Value val2
$Hash | Add-Member -MemberType NoteProperty -Name key3 -Value val3
于 2013-09-01T11:33:29.053 回答
1

为了与旧 PowerShell 版本兼容,您可以考虑使用此 cmdlet:

Function Order-Keys {
    param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)][HashTable]$HashTable,
        [Parameter(Mandatory = $false, Position = 1)][ScriptBlock]$Function,
        [Switch]$Descending
    )
    $Keys = $HashTable.Keys | ForEach {$_} # Copy HashTable + KeyCollection
    For ($i = 0; $i -lt $Keys.Count - 1; $i++) {
        For ($j = $i + 1; $j -lt $Keys.Count; $j++) {
            $a = $Keys[$i]
            $b = $Keys[$j]
            If ($Function -is "ScriptBlock") {
                $a = $HashTable[$a] | ForEach $Function
                $b = $HashTable[$b] | ForEach $Function
            }
            If ($Descending) {
                $Swap = $a -lt $b
            }
            Else
            {
                $Swap = $a -gt $b
            }
            If ($Swap) {
                $Keys[$i], $Keys[$j] = $Keys[$j], $Keys[$i]
            }
        }
    }
    Return $Keys
}

此 cmdlet 返回按函数定义排序的键列表:

按名称分类:

$HashTable | Order-Keys | ForEach {Write-Host $_ $HashTable[$_]}
Germany Berlin
Italy Rome
Spain Madrid
Switzerland Bern

按值排序:

$HashTable | Order-Keys {$_} | ForEach {Write-Host $_ $HashTable[$_]}
Germany Berlin
Switzerland Bern
Spain Madrid
Italy Rome

您也可以考虑嵌套哈希表:

$HashTable = @{
    Switzerland = @{Order = 1; Capital = "Berne"}
    Germany     = @{Order = 2; Capital = "Berlin"}
    Spain       = @{Order = 3; Capital = "Madrid"}
    Italy       = @{Order = 4; Capital = "Rome"}
}

例如,按(散列)顺序属性排序并返回键(国家):

$HashTable | Order-Keys {$_.Order} | ForEach {$_}

或按预定义的大写排序(降序):

$HashTable | Order-Keys {$_.Capital} -Descending | ForEach {$_}
于 2014-03-24T15:32:44.400 回答
1

这是一个对我有用的简单例程。

function sortedKeys([hashtable]$ht) {
  $out = @()
  foreach($k in $ht.keys) {
    $out += $k
  }
  [Array]::sort($out)
  return ,$out
}

以及使用它的调用

forEach($k in (& sortedKeys $ht)) {
  ...
}
于 2018-10-31T23:36:07.757 回答
-1
function global:sortDictionaryByKey([hashtable]$dictionary)
{
    return $dictionary.GetEnumerator() | sort -Property name;
}
于 2018-08-30T22:42:04.550 回答