Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Compare Error

if I type this into my Immediate Window

String.Compare("AA", "SA");

I get a result of 1

surely this is wrong? AA is less than SA so shouldn't it be -1?

I am running .NET 4

like image 446
pengibot Avatar asked Mar 01 '26 07:03

pengibot


1 Answers

In the Danish culture "AA" is treated as a single letter "Å" and alphabetically it comes after "Z".

CultureInfo cultureInfo = CultureInfo.GetCultureInfo("da-DK");
int comparision = String.Compare("AA", "SA", false, cultureInfo);
Console.WriteLine(comparision);

Result:

1

To get the result you want you can use invariant culture (or a specific culture that has the sort order that you desire):

CultureInfo cultureInfo = CultureInfo.InvariantCulture;
int comparision = String.Compare("AA", "SA", false, cultureInfo);
Console.WriteLine(comparision);

Result:

-1
like image 143
Mark Byers Avatar answered Mar 03 '26 21:03

Mark Byers



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!