使用CompareStringEx来重新排序
为了像Windows一样,对于 字符串保证排序不会乱,可以自定义排序方法。
这里采用CompareStringEx来实现。
第一步,声明CompareStringEx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | static readonly Int32 NORM_IGNORECASE = 0x00000001; static readonly Int32 NORM_IGNORENONSPACE = 0x00000002; static readonly Int32 NORM_IGNORESYMBOLS = 0x00000004; static readonly Int32 LINGUISTIC_IGNORECASE = 0x00000010; static readonly Int32 LINGUISTIC_IGNOREDIACRITIC = 0x00000020; static readonly Int32 NORM_IGNOREKANATYPE = 0x00010000; static readonly Int32 NORM_IGNOREWIDTH = 0x00020000; static readonly Int32 NORM_LINGUISTIC_CASING = 0x08000000; static readonly Int32 SORT_STRINGSORT = 0x00001000; static readonly Int32 SORT_DIGITSASNUMBERS = 0x00000008; static readonly String LOCALE_NAME_USER_DEFAULT = null ; static readonly String LOCALE_NAME_INVARIANT = String.Empty; static readonly String LOCALE_NAME_SYSTEM_DEFAULT = "!sys-default-locale" ; [DllImport( "kernel32.dll" , CharSet = CharSet.Unicode)] static extern Int32 CompareStringEx( String localeName, Int32 flags, String str1, Int32 count1, String str2, Int32 count2, IntPtr versionInformation, IntPtr reserved, Int32 param ); |
第二步,实现IComparer接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class LexicographicalComparer : IComparer<String> { readonly String locale; public LexicographicalComparer() : this (CultureInfo.CurrentCulture) { } public LexicographicalComparer(CultureInfo cultureInfo) { if (cultureInfo.IsNeutralCulture) this .locale = LOCALE_NAME_INVARIANT; else this .locale = cultureInfo.Name; } public Int32 Compare(String x, String y) { // CompareStringEx return 1, 2, or 3. Subtract 2 to get the return value. return CompareStringEx( this .locale, SORT_DIGITSASNUMBERS, // Add other flags if required. x, x.Length, y, y.Length, IntPtr.Zero, IntPtr.Zero, 0) - 2; } } |
第三步,调用如下:
1 2 | var names = new [] { "2.log" , "10.log" , "1.log" }; var sortedNames = names.OrderBy(s => s, new LexicographicalComparer()); |
作者:我也是个傻瓜
出处:http://www.cnblogs.com/liweis/
签名:成熟是一种明亮而不刺眼的光辉。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2015-03-23 读取Mat文件中的汉字代码