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

时间:2018-02-28 21:28:42

标签: arrays powershell multidimensional-array

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

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

我希望运行一个ForEach()循环或类似的函数来根据第一个元素中指示的年份对第二个元素中的数字进行总计,这样我就得到了这样的输出:

2017,159
2018,65

我如何才能最好地完成这项工作?

2 个答案:

答案 0 :(得分: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))
}

答案 1 :(得分: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"