How to delete an object that is a reference type from an ArrayList?

70 Views Asked by At

I'm trying to figure out how to achieve deletion of an object inside an ArrayList when the object is a reference type.

Consider the following code:

$leftTable =  Import-Csv -Delimiter ';' -Path "C:\temp\linux_left.csv" 
[System.Collections.ArrayList]$rightTable =  Import-Csv -Delimiter ';' -Path "C:\temp\linux_right.csv"
$finalTable = @()

foreach($line in $leftTable) {   

    $matched = Compare-Object -ReferenceObject $line -DifferenceObject $rightTable -IncludeEqual -ExcludeDifferent -Property 'asset.name','definition.id','definition.name','state'| Select-Object 'asset.name','definition.id','definition.name','state'
    if($matched)
    {
        $finalTable += $matched
        $rightTable.Remove($matched)
    }
    else
    {
        ...
    }
}

How can I make $matched matches structurally what matched in $rightTable ?

I know it has something to do with Object.Equals() method that is testing for reference equality when the Remove() method is trying to match what I want to delete, but I really don't see how can I make this working with code above?

1

There are 1 best solutions below

1
mclayton On

Posting from a phone so can’t give a full description right now, but the sample below works on tio.run…

$left = @"
aaa, bbb, ccc
a1, b1, c1
a2, b2, c2
"@ | convertfrom-csv

$right = @"
aaa, bbb, ccc
a1, b1, c1
a3, b3, c3
"@ | convertfrom-csv

$results = @()
foreach( $item in $left )
{
    $matched = @(
        $right `
            | where-object {
                ($_.aaa -eq $item.aaa) -and 
                ($_.bbb -eq $item.bbb) -and
                ($_.ccc -eq $item.ccc) 
            }
    )

    # don”t use += in production code
    # (this is just for demo purposes)
    $results += $matched

    $right = @( $right `
        | where-object {
            $_ -notin $matched
        }
    )

}

"results = "
$results | format-table

"right = "
$right | format-table

Output:

results = 

aaa bbb ccc
--- --- ---
a1  b1  c1

right = 

aaa bbb ccc
--- --- ---
a3  b3  c3

Basically it finds the objects in $right that match each item in $left and then creates a new array with those items filtered out…