首页 > 解决方案 > 需要在 Powershell 中以更快的方式将大型数组合并到单个二维数组中

问题描述

我正面临一种情况,我需要一种非常快速的方法来通过 Powershell 合并多个大型数组。最初数据来自 json 输入,但为了解释我的挑战,这里有一个小代码片段,它会产生类似的情况:

$columnCount = 10 # this number is NOT fixed!
$rowCount = 10KB
$allData = @()
$titles = @()

# create sample input data for the scenario that I need to solve:
foreach($i in 1..$columnCount) {
    $titles += "Column$i"
    $columnData = ,"$i" * $rowCount
    $alldata += ,$columnData
}

现在我需要一种快速的方法来将这 10 个一维数组及其每列的数据合并到一个具有正确列标题的单个二维数组中。

我从这段代码开始:

$t = [System.Diagnostics.Stopwatch]::StartNew()

$result = [System.Collections.ArrayList]::new()
$columnMaxId = $columnCount-1
$rowMaxId = $allData[0].count-1
foreach($row in 0..$rowMaxId) {
    $line = [PsObject]::new()
    foreach($column in 0..$columnMaxId) {
        $line | Add-Member -MemberType NoteProperty -Name $titles[$column] -Value $allData[$column][$row]
    }
    $null = $result.Add($line)
}

$t.Stop()
$t.Elapsed.TotalSeconds

上述演示数据的运行时间为 12,2429499 秒。因为我必须非常频繁地运行这种任务,而且实际数据有时甚至更大并且有多达 30 列,所以这个解决方案不够快。我怎样才能加快速度?

标签: arrayspowershellmergedatatable

解决方案


我最终使用数据表来完成上述任务。在数据表中添加行允许每行传递一个值数组,这样我就可以处理每行的动态长度。这是我的代码:

$t = [System.Diagnostics.Stopwatch]::StartNew()

$table = [System.Data.Datatable]::new()
foreach($title in $titles) {[void]$table.Columns.Add($title)}
$columnMaxId = $columnCount-1
foreach($row in 0..($rowCount-1)){
    $dataRow = [System.Collections.ArrayList]::new()
    foreach($column in 0..$columnMaxId){
        [void]$dataRow.Add($allData[$column][$row])
    }
    [void]$table.Rows.Add([array]$dataRow)
}

$t.Stop()
$t.Elapsed.TotalSeconds

上述演示输入的运行时间现在为 0,3300486 秒。


推荐阅读