The Ordering Problem of the OrderBy () function in C,

Source: Internet
Author: User

The Ordering Problem of the OrderBy () function in C,

Yesterday I encountered a very strange problem at the customer's site. I guess what the sorting output of the following code is:

static void Main(){    List<string> strs = new List<string>(){"11", "12", "1:"};    foreach(string str in strs.OrderBy(n => n))        Console.writeLine(str);}

Is that true:

11121:

No, No, No. The actual output is as follows:

1:1112

Why? The ASCII value of the colon is not 0 ~ After 9? I have no idea why C #'s default sorters are sorted in this order. Fortunately, the OrderBy () function supports custom Sorter, just change it as below.

static void Main(){    OrdinalComparer comp = new OrdinalComparer();    List<string> strs = new List<string>(){"11", "12", "1:"};    foreach(string str in strs.OrderBy(n => n, comp))        Console.writeLine(str);}public class OrdinalComparer: System.Collections.Generic.IComparer<String>{    public int Compare(String x, String y)    {        return string.CompareOrdinal(x, y);    }  }

However, I still don't know why the default OrderBy sorting should be set to this. The default sorting of Python2.3 is based on ASCII code. This causes me to write the same algorithm with others, and the output results of python and C # are inconsistent. Can anyone familiar with CLR tell me why?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.