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'?

+6
source share
3 answers

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

+10
source

Here is another use case for script blocks (anonymous delegates):

 $foo.RemoveAll( {$args[0].Name -clike 'F*'} ) 
+4
source

Turns out I really need the .clear () method, not RemoveAll. RemoveAll is required only if you want to remove a group of elements, and not all elements in the list.

0
source

Source: https://habr.com/ru/post/915212/


All Articles