C# OrderBy 排序与 Windows 资源管理器排序不一致的问题

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Runtime.InteropServices;
 4 
 5 public class NaturalComparer : IComparer<string>
 6 {
 7   [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
 8   private static extern int StrCmpLogicalW(string psz1, string psz2);
 9 
10   public int Compare(string x, string y)
11   {
12     // 使用Windows API的自然排序函数
13     return StrCmpLogicalW(x, y);
14   }
15 }
16 
17  
18 
19 //应用
20 OrderBy(f => f, new NaturalComparer()).ToList();

 

这个问题很常见,主要是因为 Windows 资源管理器使用了一种特殊的排序算法,称为 "自然排序"(Natural Sort),而 C# 的 OrderBy 默认使用的是字典序排序 (Lexical Sort)。

排序差异示例

例如,对于文件名列表:file1.txtfile10.txtfile2.txt

 

    • C# OrderBy 默认排序:file1.txtfile10.txtfile2.txt(按字典序)
    • Windows 资源管理器排序:file1.txtfile2.txtfile10.txt(按自然序)
posted @ 2025-06-12 09:51  山菜的日记本  阅读(37)  评论(0)    收藏  举报