2009-12-22 34 views
8

我有一個字符串數組。不知道是否有簡單的方法來獲得在數組中找到的項目的索引?PS:獲取數組列表中的索引

# example array 
$array = "A", "B", "C" 
$item = "B" 
# the following line gets null, any way to get its index? 
$index = $array | where {$_ -eq $item} | ForEach-Object { $_.Index } 

我可以做一個循環。不確定是否有其他方法?

回答

11

使用for循環(或迭代遍歷數組索引...相同區別的foreach循環)。我不知道任何在foreach循環中保存當前數組索引的系統變量,我不認爲它存在。

# example array 
$array = "A", "B", "C" 
$item = "B" 
0..($array.Count - 1) | Where { $array[$_] -eq $item } 
+1

不錯。如果數組中有兩個「B」,則結果將是一個索引值數組。 – 2009-12-22 18:15:44

2

使用Where-Object實際上更可能是緩慢的,因爲它涉及一個簡單操作的管道。

要做到這一點,我知道(在PowerShell中V2)的最快/最簡單的方法是指派的結果的變量

$needle = Get-Random 100 
$hayStack = 1..100 | Get-Random -Count 100 
$found = for($index = 0; $index -lt $hayStack.Count; $index++) { 
    if ($hayStack[$index] -eq $needle) { $index; break } 
} 
"$needle was found at index $found" 
24

如果您知道該值在只發生一次陣,[數組] ::的IndexOf()方法是去一個好方法:

$array = 'A','B','C' 
$item = 'B' 
$ndx = [array]::IndexOf($array, $item) 

除了是簡潔,重點突出,如果陣列是非常大的這種方法的表現頗有幾分比使用像Where-Object這樣的PowerShell cmdlet更好。但是,它只會查找指定項目的第一個匹配項。但是你可以使用的IndexOf的其他重載找到下一個出現:

$ndx = [array]::IndexOf($array, $item, $ndx+1) 

$ NDX將是-1,如果該項目沒有找到。