Forum Discussion
Sorting a Hastable by Key
Hello together,
I try to sort a hastable by key(s) but have no luck.
About my hastable, the key is a string and the value is a psobject of pair of data.
So what i dit to sort the hastbale is somthing like this:
$myHashTable = @{}
....
# fill the hashtable with my objects
$myHashTable .Add("1", $MyPsObject)
$myHashTable .Add("5", $MyPsObject)
$myHashTable .Add("3", $MyPsObject)
$myHashTable .Add("2", $MyPsObject)
$myHashTable .Add("4", $MyPsObject)
....
# Sort the HashTable
$myHashTable = $myHashTable.getEnumerator() | Sort-Object -property key
As soon as it is sortet, it is not longer a hashtable with all the members etc. After the sort the variable is a DictionaryEntry and i haven't any of the hashtable members i need.
So can you please help me to sort my hashtable by key and after the sorting i can use the members for hashtables as well with it?
Thank you,
Nico
Simply create it as an ordered one? Although it's technically "OrderedDictionary" and not "hashtable", it works pretty much the same.
VasilMichev is right, there's actually no way to guarantee the order of a hashtable. I come up against this all the time when using them to create PSCustomObjects and wanting to control the order of the properties.
Instead you'll want to use an ordered dictionary, in most cases you won't notice a difference (and if you do I'd love to hear about the use case!)
If you want to jump straight to creating an ordered dictionary, add an [ordered] when you're initiating it:
$myHashTable = [ordered] @{}
If you can't control the order in which you're adding items you can sort a hashtable into an ordered dictionary:
# Standard hashtable $myHashTable = @{} # Fill with random ordered data $myHashTable.Add("1", 'Test1') $myHashTable.Add("5", 'Test5') $myHashTable.Add("3", 'Test3') $myHashTable.Add("2", 'Test2') $myHashTable.Add("4", 'Test4') # Create an ordered dictionary $orderedDictionary = [ordered] @{} # Sort the keys, add key and ke's value to dictionary foreach ($Key in ($myHashTable.Keys | Sort-Object)) { $orderedDictionary.Add($Key, $myHashTable.$Key) }
- Nico_GCopper Contributor
First of all thank you for aour answer and your sample.
I will try to change my code and hope it will work. I let you know the outcome.
br,
Nico