Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .NET sort special characters?

Tags:

c#

.net

sorting

Why does .NET sort the characters '+' and '^' in a different order than they appear in ASCII table or the way SQL sorts them.

In ASCII table '+' has value of 42 and '^' has value of 94 but if you run code like this:

var list = new List<string> { "+", "^", "!" };
list.Sort();

The list will contain values in the following order:

{ "!", "^", "+" }

LINQ sort generates the same result. Can someone tell me what kind of sort .NET does?

like image 252
Vadim Avatar asked Jun 14 '12 17:06

Vadim


2 Answers

.NET doesn't use ASCII, it uses Unicode. When you perform a string sort, .NET (by default) uses the current culture's rules for sorting. In this case, those rules indicate that "^" comes before "+". You can get the result you expect by using the "ordinal" string comparer:

var list = new List<string> { "+", "^", "!" };
list.Sort(StringComparer.Ordinal); // Order is "!", "+", "^"
like image 109
dlev Avatar answered Oct 21 '22 22:10

dlev


This is defined by the current culture set, defined in the CompareInfo property. Each culture has culture-specific sorting rules for strings.

like image 41
Reed Copsey Avatar answered Oct 21 '22 20:10

Reed Copsey