How to remove everything when using the shared list <T> in powershell
If I use a generic list as follows:
$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 to apply RemoveAll () method for List<T>
? Can I use predicates? How can I, for example, delete all elements starting with capital 'F'?
I think the only way is without using System.Predicate
, which needs delegates (sorry, but I really can't figure out how to create anonymous delegates in powershell) and use the where-object clause.
In my example, I reassign the result to the same $foo
variable, which should be added to list<T>
again.
To avoid errors, if the result counter is equal to only one, it needs a "," to always create an array
value
[system.collections.generic.list[object]]$foo = , ( $foo | ? {$_.name -cnotmatch "^f" })
EDIT:
After some test, I found how to use the lambda expression using powershell scriptblock:
$foo.removeAll( { param($m) $m.name.startswith( 'F', $false , $null) })
This is the correct way to use a method that needs System.Predicate
in powershell