Rob*_*ere 4 indexing powershell dictionary hashtable indexof
我在 powershell 中的哈希表/字典方面遇到了一些麻烦。最近的障碍是在有序字典中查找键的索引的能力。
考虑以下示例:
$dictionary = [Ordered]@{
'a' = 'blue';
'b'='green';
'c'='red'
}
Run Code Online (Sandbox Code Playgroud)
如果这是一个普通数组,我就可以使用 IndexOf() 查找条目的索引。
[array]::IndexOf($dictionary,'c').
Run Code Online (Sandbox Code Playgroud)
正常情况下会返回 2。
不过,如果我用有序字典尝试这样做,我会得到-1。
有什么解决办法吗?
编辑: 如果有人读到这篇文章想知道我在说什么。我试图使用它的目的是创建一个对象,以也具有数字顺序的方式规范化属性条目。
我试图将其用于进程的状态,例如:
$_processState = [Ordered]@{
'error' = 'error'
'none' = 'none'
'started' = 'started'
'paused' = 'paused'
'cleanup' = 'cleanup'
'complete' = 'complete'
}
Run Code Online (Sandbox Code Playgroud)
如果您能够轻松做到这一点,则上述对象将给出$_processState.error索引值 0 并逐个条目递增,最终给出$_processState.complete索引值 5。然后,如果您通过“索引值”比较两个属性,您可以看到哪个属性一种是通过简单的操作员进一步发展。例如:
$thisObject.Status = $_processState.complete
If ($thisObject.Status -ge $_processState.cleanup) {Write-Host 'All done!'}
PS > All done!
Run Code Online (Sandbox Code Playgroud)
^^这不能按原样工作,但这就是想法。这就是我的目标。或者也许找到类似 $_processState.complete.IndexNumber() 的东西
拥有这样的对象还可以让您通过索引名称本身分配值,同时标准化选项......
$thisObject.Status = $_processState.paused
$thisObject.Status
PS > paused
Run Code Online (Sandbox Code Playgroud)
不太确定这是当时最好的方法,或者它是否仍然是 PS v5 中提供的所有自定义类选项的最佳方法。
它可能不会比 Frode F. 的答案更有效,但也许更简洁(内联)只是将哈希表的keys集合放入子表达式 ( $()) 中,然后对结果调用 indexOf 。
你的具体表达方式很简单:
$($dictionary.keys).indexOf('c')
Run Code Online (Sandbox Code Playgroud)
2...这给出了您期望的值。这在常规哈希表上也同样有效......当然,除非哈希表以几乎任何方式修改......所以在这种情况下它可能不是很有用。
使用这个哈希表(它还显示了许多编码方法4......):
$hashtable = [ordered]@{
sample = 'hash table'
0 = 'hello'
1 = 'goodbye'
[char]'4' = 'the ansi character 4 (code 52)'
[char]4 = 'the ansi character code 4'
[int]4 = 'the integer 4'
'4' = 'a string containing only the character 4'
5 = "nothing of importance"
}
Run Code Online (Sandbox Code Playgroud)
将产生以下表达式/结果对:
# Expression Result
#------------------------------------- -------------
$($hashtable.keys).indexof('5') -1
$($hashtable.keys).indexof(5) 7
$($hashtable.keys).indexof('4') 6
$($hashtable.keys).indexof([char]4) 4
$($hashtable.keys).indexof([int]4) 5
$($hashtable.keys).indexof([char]'4') 3
$($hashtable.keys).indexof([int][char]'4') -1
$($hashtable.keys).indexof('sample') 0
Run Code Online (Sandbox Code Playgroud)
顺便一提:
[int][char]'4'等于[int]52[char]'4'具有 的“值”(大小?)52,但它是一个字符,因此它被这样使用...一定喜欢打字系统,虽然很灵活,但如果你不小心的话,有时会变得非常糟糕。
| 归档时间: |
|
| 查看次数: |
12442 次 |
| 最近记录: |