简体   繁体   English

具有多个条件的数组的唯一元素

[英]Unique elements of an array with multiple criteria

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 乔120

Joe 111 乔111

Joe 89 乔89

Joe 45 乔45

Kyle 500 凯尔500

Kyle 300 凯尔300

Kyle 120 凯尔120

Kyle 60 凯尔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. 这是一个具有60k行的相当大的数据集。 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: 要在desc中设置数值,您需要一些技巧:

$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 | $ 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. 我将为此使用Group-Object ,然后从该结果中选择最高的数值。

$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 . Group-Object Name将为每个原始Name创建一个唯一条目,作为名为Name的新属性。 Each entry has a Group property that contains all objects that have the same Name value and the corresponding Money values. 每个条目都有一个Group属性,其中包含具有相同Name值和相应Money属性值的所有对象。

Select-Object displays the Name property and a calculated Money property. Select-Object显示“ Name属性和计算出的“ Money属性。 The Money property takes the array of money values, casts them to type [int] , and then sorts in descending order. Money属性采用货币值数组,将其强制转换为[int]类型,然后以降序排序。 Since you only want the highest value, only the first element of the array [0] is selected. 由于只需要最大值,因此仅选择数组[0]的第一个元素。

Use a hashtable to hold the maximum value per Name value: 使用哈希表保存每个Name值的最大值:

$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: $maxValues哈希表现在将保存每个名称的最大数量:

PS C:\> $maxValues

Name                           Value
----                           -----
Joe                            120
Kyle                           500

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM