c# - PowerShell 排序顺序不正确

标签 c# powershell sorting

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

相关文章:

windows - 如何在 WinCC OA 中将 system() 与 rxrepl 一起使用?

powershell - 无法删除变量,因为它已被优化且不可删除 - 释放 COM 对象

python - 在 2 个列表中查找最接近的日期时间

java - 排序算法

c# - CS0117 C# 'Resource' 不包含 'Drawable' 的定义

c# - 发件人未收到 UDP 广播

c# - C#中非整数的内存数组中最大可能

c# - 另一个未更新的 MVVM 可见性属性

powershell - 如何将多行字符串转换为对象或数组?

php - 按数组中最后一个键的值排序?