Gor*_*don 4 powershell ordereddictionary array-indexing
给定一个有序字典,我想获取索引 0 处的键。我当然可以执行一个循环,获取第一次迭代的键并立即跳出循环。但我想知道是否有办法直接做到这一点?我的 Google-Fu 没有发现任何东西,在黑暗中的一些拍摄也失败了。我尝试过类似的事情
$hash[0].Name
Run Code Online (Sandbox Code Playgroud)
和
$hash.GetEnumerator()[0].Name
Run Code Online (Sandbox Code Playgroud)
我发现了关于在 C# 中执行此操作的讨论,这导致了这个
[System.Collections.DictionaryEntry]$test.Item(0).Key
Run Code Online (Sandbox Code Playgroud)
但这也失败了。这只是无法完成的事情,还是我走错了路?
使用.Keys集合:
$orderedHash = [ordered] @{ foo = 1; bar = 2 }
# Note the use of @(...)
@($orderedHash.Keys)[0] # -> 'foo'
Run Code Online (Sandbox Code Playgroud)
笔记:
使用@(...)数组子表达式运算符 枚举集合.Keys并将其元素收集到[object[]]数组中,从而可以通过位置索引进行访问。
集合.Keys本身只实现了System.Collections.ICollection接口,支持枚举,但不支持索引访问。
@(...)在 PowerShell (Core) 7.3+ (.NET 7+) 中不再需要启用索引,这要归功于iRon通过GitHub 问题 #56835发起的改进:.Keys然后该集合将实现该System.Collections.IList接口,该接口确实支持位置索引。请注意,此更改仅适用于 有序哈希表 ( [ordered] @{ ... }, System.Collections.Specialized.OrderedDictionary),不适用于常规(无序)哈希表( @{ ... }) 或实现该System.Collections.IDictionary接口的其他类型。然而,iRon 已经创建了一个后续提案,以使该.Keys属性可对所有(定义)有序和排序字典进行索引- 请参阅GitHub 问题 #63537。
.Name是 PowerShell 提供的别名属性;System.Collections.DictionaryEntry包含每个键的类型本机属性是.Key