Florin M
Florin M

Reputation: 445

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?

EDIT:

 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.

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

Upvotes: 2

Views: 2294

Answers (3)

Harry
Harry

Reputation: 5707

Two characters are compared by their ASCII or Unicode value.

ASCII table: http://www.theasciicode.com.ar/american-standard-code-information-interchange/ascii-codes-table.png

So ('A' is 65) is considered greater than ('a' is 97) b'coz 65 comes BEFORE 97. You can lookup ASCII code of each character in your array in the table above. (And your array should be "char[] letters" not "string[] letters" from what I can see :D)

Upvotes: 0

sstan
sstan

Reputation: 36483

If for some reason you want to keep using strings, but don't want the default culture sensitive comparison, you can force an "ASCII" sort by adding the IComparer parameter to the call to OrderBy, and specifying that you want the comparison to use the code point values for sorting:

letters.OrderBy(x => x, StringComparer.Ordinal);

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37299

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.

Upvotes: 4

Related Questions