PowerShell如何按索引逐行拼接两个数组元素(逗号分隔)
PowerShell 按索引对应拼接两个数组元素
问题场景
给定以下两个数组:
$array1 = "string01", "string02", "string03" $array2 = "another01", "another02", "another03"
需要将两个数组按索引对应逐行拼接,使$array1的第n个元素与$array2的第n个元素用逗号分隔组合,最终写入文件的期望输出为:
Example01: string01,another01 string02,another02 string03,another03
此前使用foreach循环得到的是全量元素组合(所有元素两两配对),无法实现预期效果,以下是正确的实现方法。
解决方案
方法1:使用for循环按索引遍历
这是最直观的实现方式,适配所有PowerShell版本:
# 假设两个数组长度相同,若长度不同可先取最小长度避免索引越界 $result = for ($i = 0; $i -lt $array1.Count; $i++) { "$($array1[$i]),$($array2[$i])" } # 将结果写入目标文件 "Example01:" | Out-File -Path "output.txt" -Encoding utf8 $result | Out-File -Path "output.txt" -Encoding utf8 -Append
方法2:使用LINQ的Zip方法(简洁版)
通过调用.NET的LINQZip方法,可直接将两个数组对应索引的元素配对,代码更简洁:
# 利用Zip方法自动配对对应索引的元素,拼接成目标格式 $result = [System.Linq.Enumerable]::Zip( $array1, $array2, [System.Func[string, string, string]]{ "$($args[0]),$($args[1])" } ) # 写入文件 "Example01:" | Out-File -Path "output.txt" -Encoding utf8 $result | Out-File -Path "output.txt" -Encoding utf8 -Append
处理数组长度不一致的情况
如果两个数组长度不同,可先取两者的最小长度,避免出现索引越界错误:
$minLength = [Math]::Min($array1.Count, $array2.Count) $result = for ($i = 0; $i -lt $minLength; $i++) { "$($array1[$i]),$($array2[$i])" }
为什么之前的foreach无法实现?
普通嵌套foreach会遍历第一个数组的每个元素,再遍历第二个数组的所有元素,最终生成全量元素组合(如string01,another01、string01,another02等),而非按索引对应的配对结果,因此需要通过索引遍历或Zip方法来实现需求。
内容的提问来源于stack exchange,提问作者Alexandre Beck
相关产品推荐
相关产品推荐

