2016-01-29 30 views
0

在arraylist中添加字符串元素並找到它的索引值?需要在powershell中的arraylist中添加和查找元素索引值?

[code...] 
$eventList = New-Object System.Collections.ArrayList 
$eventList.Add("Hello") 
$eventList.Add("test") 
$eventList.Add("hi") 

不工作引發的錯誤: -

Method invocation failed because [System.String[]] doesn't contain a method named 'Add'. 
At C:\Users\Administrator\Desktop\qwedqwe.ps1:9 char:15 
+ $eventList.Add <<<< ("Hello") 
    + CategoryInfo   : InvalidOperation: (Add:String) [], RuntimeException 
    + FullyQualifiedErrorId : MethodNotFound 
+3

這工作得很好。你能否顯示腳本的前七行? –

+0

我正在使用這些方法來查找索引值,但無法找到它...請幫助我嗎? 1. $ index = $ evenList.FindIndex({param($ s)$ s -match'cv [u-z]'}); 2.(0 ..($ eventList.Count-1))|其中{$ eventList [$ _] -eq'hi'} 3。 [array] :: indexof($ eventList,'hi') –

+0

'ArrayList'沒有實現FindIndex() - 確定它不應該是List [string]'?再次,請向我們展示整個上下文 –

回答

1

正如評論(或其他IDE)中提到,如果你開發這個在ISE和以前用一個類型轉換分配$eventList,像這樣:

[string[]]$eventList = @() 

或相似,註釋掉前面的行不會幫助你 - 變量已經存在,將有該類型綁定到它在其生命週期的剩餘部分。

您可以Remove-Variable eventList


刪除任何以前的任務一旦你得到了排序,我們可以繼續以實際定位的指數。如果你有興趣的精確匹配的索引,使用IndexOf()

PS> $eventList.IndexOf('hi') 
2 

如果不夠靈活,使用a generic List<T>,它實現FindIndex()

FindIndex()需要謂詞 - 即基於輸入(在列表中的項目)返回$true$false功能:

$eventList = New-Object System.Collections.Generic.List[string] 
$eventList.Add("Hello") 
$eventList.Add("test") 
$eventList.Add("hi") 
$predicate = { 
    param([string]$s) 

    return $s -like 'h*' 
} 

然後調用FindIndex()$predicate功能作爲唯一的參數:

(它匹配Hello在索引0處,因爲它與一個h開始)

+0

$ eventList = New-Object System.Collections.ArrayList $ eventList.Add(「Hello」) $ eventList.Add(「測試 「) $ eventList.Add(」 HI「) $ eventList.GetType()。全名 [數組] ::的indexOf($ EVENTLIST, '嗨')我現在用新的標籤,但仍然是這個代碼顯示此錯誤無法找到「IndexOf」的過載和參數計數:「2」。 在行:8字符:17 + [陣列] ::的indexOf <<<<($一個, '黃色') + CategoryInfo:NotSpecified:(:) [],MethodException + FullyQualifiedErrorId:MethodCountCouldNotFindBest –

+0

或者可以ü請給我樣本來找到一個arraylist元素的位置? –

+0

@LovepreetSingh我已經更新了答案,'ArrayList'和'List '都實現了'IndexOf()',你不需要調用'[array] :: IndexOf()' –