PowerShell foreach()基于第一个元素的多维数组

问题描述 投票:1回答:2

我有一个相当基本的多维数组,看起来像这样:

2017,123 
2017,25
2018,5
2018,60
2017,11

我希望运行一个ForEach()循环或类似的函数来根据第一个元素中指示的年份对第二个元素中的数字进行总计,这样我最终会产生如下输出:

2017,159
2018,65

我怎样才能做到最好?

arrays powershell multidimensional-array
2个回答
2
投票

以下解决方案简洁但不快:

# input array
$arr = 
  (2017,123),
  (2017,25),
  (2018,5),
  (2018,60),
  (2017,11)

# Group the sub-arrays by their 1st element and sum all 2nd elements
# in each resulting group.
$arr | Group-Object -Property { $_[0] } | ForEach-Object {
  , ($_.Name, (($_.Group | ForEach-Object { $_[1] } | Measure-Object -Sum).Sum))
}

0
投票

假设您的数组看起来像“$ array”,这将为您提供所需的内容:

$2017total = 0
$2018total = 0

$array = "2017,123",
"2017,25",
"2018,5",
"2018,60",
"2017,11" | % { 

if ($_ -match '2017') {
    $2017 = ($_ -split ',')[1]
    $2017total += $2017
}
else {
    $2018 = ($_ -split ',')[1]
    $2018total += $2018
} 
}

Write-Host "2017,$2017total"
Write-Host "2018,$2018total"
© www.soinside.com 2019 - 2024. All rights reserved.