排序散列 table(散列 tables)

Sorting hash table (of hash tables)

我在尝试获取哈希 table 的哈希 table 进行排序时遇到了困难。似乎排序的行为正在将散列 table 变成其他东西,我无法遍历新结构。

$mainHashTable = @{}
$mainHashTable.Add('B', @{'one'='B1'; 'two'='B2'; 'three'='B3'})
$mainHashTable.Add('D', @{'one'='D1'; 'two'='D2'; 'three'='D3'})
$mainHashTable.Add('A', @{'one'='A1'; 'two'='A2'; 'three'='A3'})
$mainHashTable.Add('C', @{'one'='C1'; 'two'='C2'; 'three'='C3'})

CLS
$mainHashTable
foreach ($hashtable in $mainHashTable.keys) {

    foreach ($itemKey in $mainHashTable.$hashtable.keys) {
        Write-Host "$itemKey $($mainHashTable.$hashtable.$itemKey)!"
    }
}
Write-Host
$sortedHashTable = $mainHashTable.GetEnumerator() | sort-object -property name
$sortedHashTable
foreach ($hashtable_S in $sortedHashTable.keys) {
    foreach ($itemKey_S in $sortedHashTable.$hashtable_S.keys) {
        Write-Host "$itemKey_S $($sortedHashTable.$hashtable_S.$itemKey2)!"
    }
}

$mainHashTable$sortedHashTable 转储到控制台的两行看起来一切正常。但是第二个循环集什么都不做。我试过这样投射

$sortedHashTable = [hashtable]($mainHashTable.GetEnumerator() | sort-object -property name)

这只会引发错误

Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Hashtable".

那么,是否有某种方法可以将系统对象转换为散列 table,以便循环结构对排序后的结果起作用?还是我最好学习走 System.Object 的结构?并且(也许在学术上),有没有办法对哈希 table 进行排序并取回哈希 table?

您当前正在做的是将哈希表拆分为单独条目的列表(通过 .GetEnumerator()),然后对 that 进行排序 - 所以您最终得到 $sortedHashTable 只是 key/value 对对象的数组,按键排序,而不是实际的 [hashtable].

is there a way to sort a hash table and get back a hash table?

否 - 您不能 "sort a hash table" 内联,因为哈希表不保留任何保证的键顺序。

这里的方法是将条目复制到 有序 字典中,顺序为:

$sortedHashTable = [ordered]@{}

# Sort the keys, then insert into our ordered dictionary
foreach($key in $mainHashTable.Keys |Sort-Object){
    $sortedHashTable[$key] = $mainHashTable[$key]
}