Sort Hashtable and assign it to a new variable in Powershell

百般思念 提交于 2020-01-23 16:59:13

问题


I would like to know how to assign a sorted hasttable using the following command to a new variable. I am using the following command

$ht =   @{ 
           1 = "Data1"; 
           3 = "Data3"; 
           2 = "Data2"; 
         }

$htSorted = $ht.GetEnumerator() | Sort-Object Name

but after running it i can't traverse on the resultant hashtable

foreach($key in $htSorted.Keys)
{
     $item[$key]
}

Any idea ?


回答1:


In case you need to have a sorted hashtable, you can use SortedDictionary. Example:

$s = New-Object 'System.Collections.Generic.SortedDictionary[int, string]'
1..20 | % { 
  $i = (Get-Random -Minimum 0 -Maximum 100)
  write-host $i
  $s[$i] = $i.ToString() 
}
$s

I created 20 random values and stored them in the dictionary. Then when PowerShell is going through the dictionary (via GetEnumerator()), the values are sorted by keys.

It will be probably much faster than using old hashtable and sorting via Sort-Object.




回答2:


After running $htSorted.GetType() and $htSorted | GetMembers, It turns out that the Sort-Object cmdlet returns an arrary of dictionary entries. Hence i can travers it simply as follows:

foreach($item in $htSorted)
{
     $item.Key
     $item.Value    
}



回答3:


Answer to the OP:

You are setting up the sorted "hashtable" correctly but then you write:


foreach($key in $htSorted.Keys)
{
     $item[$key]
}

In order to iterate through the sorted "hashtable" please use the following code:


foreach($item in $htSorted.GetEnumerator())
{
     write-host $item.key
     write-host $item.value
}

As I also heard that a sorted hastable by nature cannot exist, I don't know what kind of object this is after putting it through the sort-object. But at least it behaves just like a sorted hashtable :-)



来源:https://stackoverflow.com/questions/4656289/sort-hashtable-and-assign-it-to-a-new-variable-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!