You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:33:25