无法在Powershell中对通用词典(按键)进行排序

问题描述 投票:1回答:1

我无法通过SORTED集合获取循环以使用通用字典。

显然,我想得到:

11, Wisconsin
21, Virginia
31, North Carolina
41, Alaska

但是下面的两个不同的尝试没有。

$myGenericDictionary = New-Object 'system.collections.generic.dictionary[[int],[string]]'

$myGenericDictionary.Add(21, "Virginia")
$myGenericDictionary.Add(31, "North Carolina")
$myGenericDictionary.Add(41, "Alaska")
$myGenericDictionary.Add(11, "Wisconsin")

foreach ($item in $myGenericDictionary.Keys.GetEnumerator() | Sort-Object Key)
{
    #Write-Output $item.GetType().FullName 
    #$item.PSObject.Properties
    #[System.Collections.Generic.KeyValuePair[[int],[string]]] $currentKvp = $item
    Write-Output $item
    [int]$currentKey = $item
    [string]$currentValue = $myGenericDictionary[$currentKey]

    WriteDebugMsg ("Trying to Order These By Key (using GetEnumerator) .   Key:" + $currentKey + ", Value:" + $currentValue)
}


$sortedMyGenericDictionary = New-Object 'system.collections.generic.dictionary[[int],[string]]'
$sortedMyGenericDictionary = $myGenericDictionary | Sort-Object -Property Key

foreach ($item in $sortedMyGenericDictionary.Keys)
{
    Write-Output $item
    [int]$currentKey = $item
    [string]$currentValue = $myGenericDictionary[$currentKey]

    WriteDebugMsg ("Trying to Order These By Key (using a separate collection).   Key:" + $currentKey + ", Value:" + $currentValue)
}
powershell powershell-v3.0
1个回答
1
投票

感谢user2864740

foreach ($item in $myGenericDictionary.GetEnumerator() | Sort-Object Key) #change here
{
    Write-Output $item
    [int]$currentKey = $item.Key #change here
    [string]$currentValue = $myGenericDictionary[$currentKey]

    WriteDebugMsg ("Trying to Order These By Key (using GetEnumerator) .   Key:" + $currentKey + ", Value:" + $currentValue)
}
© www.soinside.com 2019 - 2024. All rights reserved.