Home > Back-end >  OrderedDictionary key name at specified index
OrderedDictionary key name at specified index

Time:01-08

Given an ordered dictionary, I would like to get the key at index 0. I can of course do a loop, get the key of the first iteration and immediately break out of the loop. But I wonder if there is a way to do this directly? My Google-Fu has not turned up anything, and some shots in the dark have failed too. I have tried things like

$hash[0].Name

and

$hash.GetEnumerator()[0].Name

I found this discussion about doing it in C#, which lead to this

[System.Collections.DictionaryEntry]$test.Item(0).Key

but that fails too. Is this just something that can't be done, or am I going down the wrong path?

CodePudding user response:

Use the .Keys collection:

$orderedHash = [ordered] @{ foo = 1; bar = 2 }

# Note the use of @(...)
@($orderedHash.Keys)[0] # -> 'foo'

Note:

  •  Tags:  
  • Related