I have an array that has objects with multiple properties. I use two of them for sorting, eg name and a numeric value (descending):
Joe 120
Joe 111
Joe 89
Joe 45
Kyle 500
Kyle 300
Kyle 120
Kyle 60
etc.
I collect these from multiple sources, so have my array with similar count for each name.
I only need the first line for each name - the largest numeric value.
It is a fairly large data set with 60k lines. Tried to foreach through the whole with matching the list of users and selecting the first instance. Painfully slow
To set the numeric value in desc you need some trick:
$sorted = $array | Sort-Object Name, @{Name='Money';expression = {$_.Money};Ascending = $false }
However, unique switch would only work with one element. But if I do:
$sorted | Sort-Object -Property Name -Unique
this messes up the previous sort that used two criteria, so I am not getting the largest value for that username :(
I would use Group-Object
for this and then select the highest numeric value from that result.
$array | Group-Object Name |
Select-Object Name,@{n='Money';e={([int[]]$_.Group.Money | Sort-Object -Descending)[0]}}
Explanation:
Group-Object Name
will create a unique entry for each original Name
as a new property called Name
. Each entry has a Group
property that contains all objects that have the same Name
value and the corresponding Money
values.
Select-Object
displays the Name
property and a calculated Money
property. The Money
property takes the array of money values, casts them to type [int]
, and then sorts in descending order. Since you only want the highest value, only the first element of the array [0]
is selected.
Use a hashtable to hold the maximum value per Name
value:
$maxValues = @{}
foreach($value in $array){
if($maxValues[$value.Name] -ge $value.Money){
# amount is smaller, skip updating
continue
}
$maxValues[$value.Name] = [int]$value.Money
}
The $maxValues
hashtable will now hold the maximum amount per name:
PS C:\> $maxValues
Name Value
---- -----
Joe 120
Kyle 500
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.