IComparer for natural sorting [duplicate]

﹥>﹥吖頭↗ 提交于 2019-11-29 04:18:35

If you have LINQ, you can use OrderBy:

Regex digitPart = new Regex(@"^\d+", RegexOptions.Compiled);
...
myList.OrderBy(x => int.Parse(digitPart.Match(x).Value))
John Arlen

The easiest is to wrap the Win32 API call as explained in https://stackoverflow.com/a/248613/631687

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class NumStrCmp : IComparer<string> {
    public int Compare(string x, string y){
        Regex regex = new Regex(@"(?<NumPart>\d+)(?<StrPart>\D*)",RegexOptions.Compiled);
        var mx = regex.Match(x);
        var my = regex.Match(y);
        var ret = int.Parse(mx.Groups["NumPart"].Value).CompareTo(int.Parse(my.Groups["NumPart"].Value));
        if(ret != 0) return ret;
        return mx.Groups["StrPart"].Value.CompareTo(my.Groups["StrPart"].Value);
    }
}

class Sample {
    static public void Main(){
        var data = new List<string>() {"10","10b","1111","1164","1174","23","23A","23B","23D","23E"};
        data.Sort(new NumStrCmp());
        foreach(var x in data){
            Console.WriteLine(x);
        }
   }
} 

I hope this link will helps you for natural sorting using natural Sort Comparer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!