3

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

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
pengibot
  • 1,492
  • 3
  • 15
  • 35
  • 1
    I get -1: http://rextester.com/WUDDT41321 – Jamiec Sep 27 '12 at 11:37
  • That's what's confusing to me, I don't understand why it is returning the wrong result. – pengibot Sep 27 '12 at 11:38
  • When possible, the application should use string comparison methods that accept a CompareOptions value to specify the kind of comparison expected. As a general rule, user-facing comparisons are best served by the use of linguistic options (using the current culture), while security comparisons should specify Ordinal or OrdinalIgnoreCase. [MSDN](http://msdn.microsoft.com/en-us/library/system.globalization.compareoptions.aspx) – V4Vendetta Sep 27 '12 at 11:40
  • Yes it was a culture issue, turns out in Danish there is a letter 'AA' in their alphabet which appears after 'SA'. It is to display a list in order for users so guess if they are use to that I will keep it the way it is. – pengibot Sep 27 '12 at 11:49

1 Answers1

7

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
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452