我无法通过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)
}
感谢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)
}