Array remove element

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of DrachNeaula DrachNeaula 3 years, 7 months ago.

  • Author
    Posts
  • #11221
    Profile photo of wantto wantto
    wantto wantto
    Participant

    i have array :

    Clear-Host;
    $arr=@();
    Add-Type @'
    public class MyObject2
    {
    public int MyField = 5;
    public void xTimesMyField(int x) {
    MyField=x;
    }
    }
    '@
    for( $i=1;$i -le 10;++$i){
    $object = New-Object MyObject2;
    $object.xTimesMyField($i);
    $arr+=$object;
    }
    $arr

    how can i remove one of the elements of the array by theMyField property when it equales to certain value?

  • #11222
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    You can't remove elements from a .NET Array object. You can either use another type of collection (such as an ArrayList), or you can filter the elements and assign them to a new array object (even if it's in the same variable.) For example:

    $arr = $arr | Where-Object { $_.MyField -ne 'SomeValue' }
  • #11224
    Profile photo of wantto wantto
    wantto wantto
    Participant

    thanks

  • #11300
    Profile photo of DrachNeaula
    DrachNeaula
    Participant

    You can do some funky stuff with multiple assignment and recursion to remove an element.

    Removing based on what the element is.

    `
    function remove-item-list ($item,[array]$chckd_list=@(),[array]$list=(throw"the item $item was not in the list"))
    { if ($list.length -lt 1 ) { throw "the item $item was not in the list" }
    
       $check_item,$temp_list=$list
       if ($check_item -eq $item ) {
          $chckd_list+=$temp_list
          return $chckd_list }
       else {
          $chckd_list+=$check_item
          return (remove-item-list -item $item -chckd_list $chckd_list -list $temp_list )}
    }
    `

    Removing based on index number.

    `
    function remove-index-list ([int]$count=0,[int]$index,[array]$chckd_list=@(),[array]$list)
    {if (($list.length+$count-1) -lt $index ) { throw "the index is out of range" }
        $check_item,$temp_list=$list
        if ($count -eq $index) {
           $chckd_list+=$temp_list
           return $chckd_list}
        else {
           $chckd_list+=$check_item
           return (remove-index-list -count ($count + 1) -index $index -chckd_list $chckd_list -list $temp_list )}
    
    }
    `

You must be logged in to reply to this topic.