所以我尝试使用 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/