Group two object arrays into porwershell

Asked

Viewed 37 times

0

Hello,

I have two arrays of objects, I have to group them. That is, go through the list (object array) of "car" and when there are properties in the property_list array added to that object, which is an array of objects of the type Property, which is contained in an array of properties.

I want to end up with the "car" object array, with a property in the object called Properties that contains an array of properties coming from the property_list array, if car does not contain Property an empty array is inserted.

Code:

foreach($p in $car_list) {
        $Property =  $property_list.Where({$_.Id -eq $p.Id}) | Select-Object -Property Name,Value
        if(-Not (($null -eq $Property ) -And (@($Property ).Count -eq 0)) ) {
            $p = $p | Add-Member -NotePropertyMembers @{Properties=$Property }
        } else {
            $p = $p | Add-Member -NotePropertyMembers @{Properties=@()}
        }
}

The problem is that the code is not efficient. The car array reaches 200000 positions and each position is an object with several properties and the properties array also reaches these values. The script takes hours and hours to run.

Some way to optimize this array grouping?

Thank you.

1 answer

1


Maybe what is reducing your performance is the following line: $Property = $property_list.Where({$_.Id -eq $p.Id}) | Select-Object -Property Name,Value

Give me an experiment: Remove that line of its loop and a fixed value to its $Proprty. If performance improves, a way that Voce can try to improve your code is to create a dictionary where the keys are $p.Id and the value eh o $Property, so your access to the Press will be O(1).

  • Yes, it was the solution that I ended up finding. I built a hashmap where the id is the key and the properties are the value. Greatly improved the times.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.