但是当我使用OrderBy(fn => fn)时,它会将它们排序为:
1.log,10.log,2.log
我显然知道这可以通过写另一个比较者来完成,但是是否有一个更简单的方法来从字典排列顺序转变为自然排序?
编辑:目的是获得与Windows资源管理器中选择“按名称排序”相同的顺序.
解决方法 您可以使用Win32CompareStringEx
功能.在windows 7上,它支持您需要的排序. 您将使用P / Invoke:
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);
然后,您可以创建一个使用SORT_DIGITSASNUMBERS标志的IComparer:
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,0) - 2; }}
然后,您可以在各种排序API中使用IComparer:
var names = new [] { "2.log","10.log","1.log" };var sortednames = names.OrderBy(s => s,new LexicographicalComparer());
您也可以使用StrCmpLogicalW这是windows资源管理器使用的功能.自windows XP以来一直可用
[Dllimport("shlwAPI.dll",CharSet = CharSet.Unicode)]static extern Int32 StrCmpLogical(String x,String y);class LexicographicalComparer : IComparer<String> { public Int32 Compare(String x,String y) { return StrCmpLogical(x,y); }}
比较简单,但对比较少.
总结以上是内存溢出为你收集整理的c# – .NET以1,10和2开头排序字符串的最短方法是什么?全部内容,希望文章能够帮你解决c# – .NET以1,10和2开头排序字符串的最短方法是什么?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)