Forum Discussion
Nico_G
Mar 02, 2020Copper Contributor
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...
Joshua King
Mar 03, 2020MVP
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_GMar 06, 2020Copper 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