PowerShell数组选择性复制:按用户保留高价值type记录
PowerShell 筛选用户最高价值type记录的实现方法
情况1:ArrayList元素是自定义对象(推荐)
如果你的ArrayList里存储的是带有user和type属性的自定义对象,可直接用以下代码处理:
# 模拟你的ArrayList数据(实际替换成你的原数组) $originalList = [System.Collections.ArrayList]@( [PSCustomObject]@{user='user'; type='1x'}, [PSCustomObject]@{user='user1'; type='2x'}, [PSCustomObject]@{user='user2'; type='3x'}, [PSCustomObject]@{user='user3'; type='1x'}, [PSCustomObject]@{user='user3'; type='2x'}, [PSCustomObject]@{user='user4'; type='1x'}, [PSCustomObject]@{user='user4'; type='2x'}, [PSCustomObject]@{user='user4'; type='3x'}, [PSCustomObject]@{user='user5'; type='2x'}, [PSCustomObject]@{user='user5'; type='3x'} ) # 生成筛选后的新数组 $newList = $originalList | Group-Object -Property user | ForEach-Object { # 按type中的数字降序排序,取第一条(价值最高的记录) $_.Group | Sort-Object { [int]($_.type -replace '\D') } -Descending | Select-Object -First 1 } # 输出结果 $newList
代码说明:
Group-Object -Property user:将原数组按user字段分组,同一用户的所有记录归为一组Sort-Object { [int]($_.type -replace '\D') } -Descending:提取type中的纯数字部分(去掉非数字字符),转为整数后降序排序,确保价值最高的记录排在最前Select-Object -First 1:选取每组排序后的第一条记录,即该用户的最高价值记录
情况2:ArrayList元素是CSV格式字符串
如果你的ArrayList存储的是"user,type"格式的字符串,需先转换为对象再处理,最后转回字符串:
# 模拟你的ArrayList字符串数据(实际替换成你的原数组) $originalList = [System.Collections.ArrayList]@( "user,1x", "user1,2x", "user2,3x", "user3,1x", "user3,2x", "user4,1x", "user4,2x", "user4,3x", "user5,2x", "user5,3x" ) # 处理字符串数据并生成新数组 $newList = $originalList | ForEach-Object { # 拆分字符串为user和type字段 $user, $type = $_ -split ',', 2 [PSCustomObject]@{user = $user; type = $type} } | Group-Object -Property user | ForEach-Object { $_.Group | Sort-Object { [int]($_.type -replace '\D') } -Descending | Select-Object -First 1 } | ForEach-Object { # 转回CSV字符串格式 "$($_.user),$($_.type)" } # 添加表头并输出 @("user,type") + $newList
代码说明:
- 第一步
ForEach-Object将字符串拆分为自定义对象,方便后续分组排序操作 - 中间的分组、排序、筛选逻辑和情况1一致
- 最后一步
ForEach-Object将筛选后的对象转回CSV字符串格式,匹配期望的输出样式
内容的提问来源于stack exchange,提问作者gunnys
相关产品推荐
相关产品推荐

