How can I use C# to sort values numerically?

前端 未结 9 1695
醉话见心
醉话见心 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:37

    Since the comparison you want to do on the strings is different from how strings are normally compared in .Net, you will have to use a custom string string comparer

     class MyStringComparer : IComparer
            {
                public int Compare(string x, string y)
                {
                    // your comparison logic
                    // split the string using '.' separator
                    // parse each string item in split array into an int
                    // compare parsed integers from left to right
                }
            }
    

    Then you can use the comparer in methods like OrderBy and Sort

    var sorted = lst.OrderBy(s => s, new MyStringComparer());
    
    lst.Sort(new MyStringComparer());
    

    This will give you the desired result. If not then just tweak the comparer.

提交回复
热议问题