开发者

Sort Hashtable and assign it to a new variable in Powershell

开发者 https://www.devze.com 2023-02-03 09:14 出处:网络
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

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 c开发者_C百科an't traverse on the resultant hashtable

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

Any idea ?


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.


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    
}


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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号