Florin M Florin M - 1 year ago 239
C# Question

Linq OrderBy sort rule

I want to know on which rule the OrderBy method of Linq decides on how to sort a list of chars. I thought that it compares the char to each other with the help of the values they have in the Ascii table, but I tried it by myself an it was not correct. So does somebody know on which rule the sort is done?


string[] letters = { " ", "!", "+", "1", "9", "?", "A", "B", "Y", "Z", "[", "a", "b", "y", "z", "{"};
IEnumerable<string> ascending = letters.OrderBy(x => x);
// returns { " ", "!", "?", "[", "{", "+", "1", "9", "a", "A", "b", "B", "y", "Y", "z", "Z"}

I expexted to receive the same list back, but I got it with a complete new order.

I used a string array instead of a char array, so the OrderBy sorted the strings which is different than when you use chars.

Answer Source

It is ordering it fine. It is ordering it by the way it compares string (it is a string[]). If you want it to do it by the ASCII values of char it should be a char[] and not a string[]:

char[] letters = { ' ', '!', '+', '1', '9', '?', 'A', 'B', 'Y', 'Z', '[', 'a', 'b', 'y', 'z', '{', ' ', '!', '+', '1', '9' };
var descending = letters.OrderByDescending(x => x).ToList();

And also by the name of the variable I guess you want the OrderByDescending method instead.