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.txt, file10.txt, file2.txt
- C#
OrderBy 默认排序:file1.txt, file10.txt, file2.txt(按字典序)
- Windows 资源管理器排序:
file1.txt, file2.txt, file10.txt(按自然序)