If I use generic list like this:
$foo = New-Object 'system.collections.generic.list[object]'
$foo.Add((New-Object PSObject -Property @{ Name="Foo1"; }))
$foo.Add((New-Object PSObject -Property @{ Name="Foo2"; }))
$foo.Add((New-Object PSObject -Property @{ Name="foo3"; }))
How can I apply RemoveAll() method of List<T>
? Is it possible to use predicates? How can I for example remove all items that start with capital 'F'?
I think the only way is without using System.Predicate
that needs delegates (sorry, but really I can't figure out how create anonymous delegates in powershell) and use the where-object clause.
In my example I re-assign the result to same $foo
variable that need to be cast again to list<T>
.
To avoid error if result count is only one it need the ',' to create always an array
value
[system.collections.generic.list[object]]$foo = , ( $foo | ? {$_.name -cnotmatch "^f" })
EDIT:
After some test I've found how use lambda expression using powershell scriptblock:
$foo.removeAll( { param($m) $m.name.startswith( 'F', $false , $null) })
This is the right way for using method that needs System.Predicate
in powershell
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With