【发布时间】:2020-04-17 07:05:15
【问题描述】:
我看到我正在排序的哈希表出现一些看似非常奇怪的行为,然后尝试查看结果。我构建了哈希表,然后我需要根据值对该表进行排序,我看到了两个奇怪的地方。
这在课堂之外也能正常工作
$hash = [hashtable]::New()
$type = 'conformset'
$hash.Add($type, 1)
$type = 'applyset'
$hash.Add($type , 1)
$type = 'conformset'
$hash.$type ++
$hash.$type ++
$hash
Write-Host
$hash = $hash.GetEnumerator() | Sort-Object -property:Value
$hash
我看到哈希的内容两次,未排序,然后排序。 然而,当使用一个类时,它什么也不做。
class Test {
# Constructor (abstract class)
Test () {
$hash = [hashtable]::New()
$type = 'conformset'
$hash.Add($type, 1)
$type = 'applyset'
$hash.Add($type , 1)
$type = 'conformset'
$hash.$type ++
$hash.$type ++
$hash
Write-Host
$hash = $hash.GetEnumerator() | Sort-Object -property:Value
$hash
}
}
[Test]::New()
这只是将 Test 回显到控制台,与哈希表无关。我在这里的假设是,它与管道如何被中断有关,老实说,考虑到污染管道错误的常见程度,这是转移到类的一个很好的理由。因此,转向基于循环的方法,这将无法显示类中的第二个已排序、已排序的哈希表。
$hash = [hashtable]::New()
$type = 'conformset'
$hash.Add($type, 1)
$type = 'applyset'
$hash.Add($type , 1)
$type = 'conformset'
$hash.$type ++
$hash.$type ++
foreach ($key in $hash.Keys) {
Write-Host "$key $($hash.$key)!"
}
Write-Host
$hash = ($hash.GetEnumerator() | Sort-Object -property:Value)
foreach ($key in $hash.Keys) {
Write-Host "$key $($hash.$key)!!"
}
但是,非常奇怪的是,这仅显示了第一个基于循环的输出,但同时显示了两个直接转储。
$hash = [hashtable]::New()
$type = 'conformset'
$hash.Add($type, 1)
$type = 'applyset'
$hash.Add($type , 1)
$type = 'conformset'
$hash.$type ++
$hash.$type ++
foreach ($key in $hash.Keys) {
Write-Host "$key $($hash.$key)!"
}
$hash
Write-Host
$hash = ($hash.GetEnumerator() | Sort-Object -property:Value)
foreach ($key in $hash.Keys) {
Write-Host "$key $($hash.$key)!!"
}
$hash
现在的输出是
conformset 3!
applyset 1!
Name Value
---- -----
conformset 3
applyset 1
applyset 1
conformset 3
显然 $hash 正在排序。但是循环不会显示它?嗯?这是错误的行为,还是我只是不明白原因的预期行为,以及解决方法?
【问题讨论】:
-
哈希表类型不可排序。 [grin] 如果你想要一个排序的字典,使用 >>>
SortedList<TKey,TValue> Class (System.Collections.Generic) | Microsoft Docs — https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=netframework-4.8
标签: powershell sorting hashtable