4

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?

mklement0
  • 382,024
  • 64
  • 607
  • 775
Gordon
  • 6,257
  • 6
  • 36
  • 89

1 Answers1

5

Use the .Keys collection:

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

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

Note:

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Thanks, @iRon. I've added a link to the new issue to the answer. Arguably, for consistency even _unordered_ dictionaries should have indexable `.Keys` properties (don't know if there'd be concerns about unnecessary overhead). – mklement0 Jan 08 '22 at 16:36
  • 1
    Notably, `$orderedHash[0].keys` doesn't work and some mishmash of `$orderedHash.GetEnumerator() | ForEach-Object{...}` is subpar to this method. I can't believe how long it took me to find this! The best I found before stumbling upon your answer is: `$i=0; $orderedHash.GetEnumerator() | ForEach-Object{ if ($i -ne $index){++$i} $myKey = $_.key}` – bittahProfessional May 20 '22 at 16:38