I've run into a strange sorting of string list in c#:
var s = new List<string>();
s.Add("as");
s.Add("a_");
s.Add("a0");
s.Sort();
I was expecting this code to sort the list as:
a0
a_
as
It actually resulted in:
a_
a0
as
Can someone help me understand why a_ was sorted before a0 when the ASCII value of _ is 95 and the ASCII value of 0 is 48?
By default strings are sorted using CurrentCulture which uses a locale-sensitive sorting algorithm.
Use StringComparer.Ordinal to sort strings by their Unicode (not ASCII) code-points.
List<String> list = ...
list.Sort( comparer: StringComparer.Ordinal );
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