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?