在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 : MethodNotFoundadd string element in arraylist and find it's index value?
[code...] $eventList = New-Object System.Collections.ArrayList $eventList.Add("Hello") $eventList.Add("test") $eventList.Add("hi")Not working throwing error:-
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最满意答案
正如评论中所提到的,如果你在ISE(或其他IDE)中开发它并且之前$eventList使用类型转换分配了$eventList ,如下所示:
[string[]]$eventList = @()或类似的,注释掉前面的行将无法帮助你 - 变量已经存在,并且在其生命周期的剩余时间内将该类型绑定到该变量。
您可以使用Remove-Variable eventList删除任何先前的分配
一旦你对它进行了排序,我们就可以继续实际定位索引了。 如果您对完全匹配的索引感兴趣,请使用IndexOf() :
PS> $eventList.IndexOf('hi') 2如果这不够灵活,请使用实现FindIndex() 的通用List<T> 。
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*' }然后使用$predicate函数作为唯一参数调用FindIndex() :
PS> $eventList.FindIndex($predicate) 0(它在索引0处匹配Hello ,因为它以h开头)
As mentioned in the comments, if you've developing this in ISE (or another IDE) and previously assigned $eventList with a type cast, like so:
[string[]]$eventList = @()or similar, commenting out previous lines won't help you - the variable already exists and will have that type bound to it for the remainder of its lifetime.
You can remove any previous assignments with Remove-Variable eventList
Once you've got that sorted, we can move on to actually locating the index. If you're interested in the index of an exact match, use IndexOf():
PS> $eventList.IndexOf('hi') 2If that isn't flexible enough, use the a generic List<T>, which implements FindIndex().
FindIndex() takes a predicate - a function that returns $true or $false based on input (the items in the list):
$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*' }And then call FindIndex() with the $predicate function as the only argument:
PS> $eventList.FindIndex($predicate) 0(it matches Hello at index 0 because it starts with an h)
更多推荐
发布评论