首页 > 解决方案 > Powershell:每个的元组列表顺序错误?

问题描述

我正在尝试使用元组列表以特定顺序写入 txt 文件。该列表按 item1(数字)排序,并具有关联的字符串作为 item2。

使用 for each 循环,我尝试通过列表运行并将关联的字符串插入到 txt 文件中。我希望 for each 循环使用 item1 遍历列表,但是 for each 循环使用 item2 进行迭代并按字母顺序插入。

我如何确保它以正确的顺序插入笔记?

$sortedList 包含:

Item1 Item2  Length
----- -----  ------
    0 noteC       2
    1 noteD       2
    2 noteF       2
    3 noteA       2
    4 noteB       2
    5 note5       2

D:\ 驱动器包含:

noteA.pdf
noteB.pdf
noteC.pdf
noteD.pdf
noteF.pdf
note5.pdf

我正在做的简化版:

$notePath = "D:\"

$list = Get-ChildItem -Path $notePath -Recurse | `
        Where-Object { $_.PSIsContainer -eq $false -and $_.Extension -ne '.srt' }

$sortedList = New-Object System.Collections.ArrayList
ForEach($n in $list){
    if($n.name.Contains('C')) {
        $sortedList.Add([Tuple]::Create(0,$n.Name))
    } elseif($n.name.Contains('D')) {
        $sortedList.Add([Tuple]::Create(1,$n.Name))
    } elseif($n.name.Contains('F')) {
        $sortedList.Add([Tuple]::Create(2,$n.Name))
    } elseif($n.name.Contains('A')) {
        $sortedList.Add([Tuple]::Create(3,$n.Name))
    } elseif($n.name.Contains('B')) {
        $sortedList.Add([Tuple]::Create(4,$n.Name))
    } elseif($n.name.Contains('5')) {
        $sortedList.Add([Tuple]::Create(5,$n.Name))
    }
}

New-Item $notePath’\noteList.txt'

ForEach($n in $sortedList){
        $var = "Note:"+ $n.Item2 | Out-File -Append $notePath’\noteList.txt'
}

txt文件中的结果:

Note: noteA
Note: noteB
Note: noteC
Note: noteD
Note: noteF
Note: note5

我想要的结果在 txt 中:

Note: noteC
Note: noteD
Note: noteF
Note: noteA
Note: noteB
Note: note5

标签: powershellforeachtuples

解决方案


坚持 Tuple 主题,您只需要Sort-Object在处理结果之前重新排序结果:

  • 构建测试数据:
$unsortedList = New-Object System.Collections.ArrayList
$unsortedList.Add([Tuple]::Create(3, "noteA"))
$unsortedList.Add([Tuple]::Create(4, "noteB"))
$unsortedList.Add([Tuple]::Create(0, "noteC"))
$unsortedList.Add([Tuple]::Create(1, "noteD"))
$unsortedList.Add([Tuple]::Create(2, "noteF"))
$unsortedList.Add([Tuple]::Create(5, "note5"))

$unsortedList | format-table
#Item1 Item2 Length
#----- ----- ------
#    3 noteA      2
#    4 noteB      2
#    0 noteC      2
#    1 noteD      2
#    2 noteF      2
#    5 note5      2
  • 对数据进行排序
$sortedList = $unsortedList | sort-object -Property "Item1";

$sortedList | format-table
#Item1 Item2 Length
#----- ----- ------
#    0 noteC      2
#    1 noteD      2
#    2 noteF      2
#    3 noteA      2
#    4 noteB      2
#    5 note5      2

推荐阅读