删除空值并对自定义对象列表进行查找替换的有效方法

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

我有一组从 API 获得的大量数据(26000 条记录)。 一次性我正在过滤它们以删除特定字段值为

null
或空的字段。所以我从数据中删除空值。 在另一遍中我再次使用
for-each loop
转换同一特定字段中数据的数据形状,因此代码如下:

$data = $data | Where-Object { $_.myField -ne $null -and $_.myField -ne '' }

foreach ($item in $data) {
    $item.myField = $item.myField.Replace("ABC_", "")
}

我只是想看看你是否有更有效的方法来做到这一点。我在

PowerShell 5.0
,所以没有
Parallel For-Each
之类的东西。

示例输入数据:

$data = @(
    [PSCustomObject]@{Id=1; myField='2345';    Car = $null},
    [PSCustomObject]@{Id=2; myField='ABC_123'; Car = 'Pagani'},
    [PSCustomObject]@{Id=2; myField= $null; Car = 'Pagani'},
    [PSCustomObject]@{Id=2; myField= ''; Car = 'Pagani'},
    [PSCustomObject]@{Id=3; myField='ABC_456'; Car = 'KIA'}
)

预期结果示例:

$data = @(
    [PSCustomObject]@{Id=1; myField='2345';    Car = $null},
    [PSCustomObject]@{Id=2; myField='123'; Car = 'Pagani'},    
    [PSCustomObject]@{Id=3; myField='456'; Car = 'KIA'}
)
powershell
1个回答
0
投票

将循环从 2 个减少到 1 个,并且由于集合已经在内存中,没有什么比 PowerShell 中的

foreach
循环更好的了,所以:

$data = foreach ($item in $data) {
    if ([string]::IsNullOrWhiteSpace($item.myField)) {
        continue
    }

    $item.myField = $item.myField.Replace('ABC_', '')
    $item
}

我还没有测试过这个,但使用编译的正则表达式实例可能比

string.Replace
更快,可能值得一试:

$re = [regex]::new('^ABC_', [System.Text.RegularExpressions.RegexOptions]::Compiled)
$data = foreach ($item in $data) {
    if ([string]::IsNullOrWhiteSpace($item.myField)) {
        continue
    }

    $item.myField = $re.Replace($item.myField, '')
    $item
}
© www.soinside.com 2019 - 2024. All rights reserved.