How can I use C# to sort values numerically?

前端 未结 9 1516
醉话见心
醉话见心 2021-02-20 03:20

I have a string that contains numbers separated by periods. When I sort it appears like this since it is a string: (ascii char order)

3.9.5.2.1.1
3.9.5.2.1.10
3.         


        
9条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 03:36

    You can use the awesome AlphanumComparator Alphanum natural sort algorithm by David Koelle.

    Code:

    OrderBy(o => o.MyString, new AlphanumComparator())
    

    If you're gonna use the C# version change it to:

    AlphanumComparator : IComparer
    

    and

    public int Compare(string x, string y)
    

提交回复
热议问题