gpt4 book ai didi

c# - PowerShell 排序顺序不正确

转载 作者:太空狗 更新时间:2023-10-30 00:29:59 25 4
gpt4 key购买 nike

所以我尝试使用 PowerShell 对文件顶部的 C#“using”语句进行排序。对于给定的输入文件 File.cs,using 语句如下所示:

using System.Reflection;
using System.Configuration;
using System.Runtime.Caching;
using System.Linq;
using System;

我希望输出将“using System”作为第一个“using”,但实际上 Sort-Object 将其排序到底部。我怎样才能将其更改为排序到列表顶部?

function Update-UsingStatements
{
param (
[Parameter(Mandatory=$true)][string]$FilePath
)

$fileLines = Get-Content $FilePath
$contents = $fileLines | Out-String

$list = New-Object 'System.Collections.Generic.List[string]'
$contents | Select-String -pattern 'using\s[\w\.]+;' -AllMatches | ForEach-Object {$_.Matches} | ForEach-Object { $list.Add($_.Value) }
$list = $list | Sort-Object

for ($i = 0; $i -lt $list.Count; $i++)
{
$fileLines[$i] = $list[$i]
}

$fileLines | Out-File $FilePath -Encoding utf8
}

最佳答案

您获得该排序顺序是因为字符串包含尾随 ;,并且在字符表中 ;(ASCII 字符 59)位于 之后。(ASCII 字符 46)。所以排序顺序是绝对正确的,即使它不是您所期望的。

从排序所依据的属性中删除尾随分号以解决此问题:

$list = $list | Sort-Object { $_ -replace ';' }

关于c# - PowerShell 排序顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com