哈希表和关键订单

时间:2013-02-15 08:54:42

标签: powershell sorting hashtable powershell-v2.0

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

示例:

$hashtable = @{}

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

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

7 个答案:

答案 0 :(得分:44)

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

答案 1 :(得分:8)

您可以使用有序字典:

像这样:

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

答案 2 :(得分:4)

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

$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
}

答案 3 :(得分: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

答案 4 :(得分: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"}
}

E.g。按(散列)订单属性排序并返回密钥(国家/地区):

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

或按预定义的资本排序(降序):

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

答案 5 :(得分:0)

function global:sortDictionaryByKey([hashtable]$dictionary)
{
    return $dictionary.GetEnumerator() | sort -Property name;
}

答案 6 :(得分:0)

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

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

以及使用它的电话

forEach($k in (& sortedKeys $ht)) {
  ...
}