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?
.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 "!", "+", "^"
This is defined by the current culture set, defined in the CompareInfo property. Each culture has culture-specific sorting rules for strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With