Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange string sorting [duplicate]

Tags:

c#

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?

like image 626
Ido Ran Avatar asked Nov 23 '25 02:11

Ido Ran


1 Answers

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 );
like image 79
Dai Avatar answered Nov 24 '25 18:11

Dai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!