Péter
Péter

Reputation: 322

C# string array orderBy problem with accent characters

I wrote a little code where declare a string array and i try to order it with and without stringCompare, but the result always same.

With StringComparer where i use cultureInfo:

var strings = new string[] { "asd", "ásd", "álm", "alm" };
var ci = CultureInfo.GetCultureInfo("hu");
var comp = StringComparer.Create(ci, false);
Console.WriteLine(string.Join(", ", strings.OrderBy(item => item, comp)));

Without StringComparer:

var strings = new string[] { "asd", "ásd", "álm", "alm" };
Console.WriteLine(string.Join(", ", strings.OrderBy(item => item)));

Both result is:

alm, álm, asd, ásd

But the correct result will be:

alm, asd, álm, ásd

What do I do wrong?

Upvotes: 2

Views: 228

Answers (2)

Péter
Péter

Reputation: 322

I think i found the solution. If i set global CurrentCulture to "hu" or "hu-HU" then words not display in the correct order, BUT i found an extra Culture to Hungarian: "hu-HU_technl".

Link: https://learn.microsoft.com/hu-hu/windows/win32/intl/sort-order-identifiers?redirectedfrom=MSDN

Code:

CultureInfo ci = CultureInfo.GetCultureInfo("hu-HU_technl");
Thread.CurrentThread.CurrentCulture = ci;
var strings = new string[] { "brummm", "asd", "ásd", "álm", "alm" };
Console.WriteLine(string.Join(", ", strings.OrderBy(item => item)));

Result: alm, asd, álm, ásd, brummm

You can also reach this with StringComparer:

CultureInfo ci = CultureInfo.GetCultureInfo("hu-HU_technl");
var comp = System.StringComparer.Create(ci, false);
var strings = new string[] { "brummm", "asd", "ásd", "álm", "alm" };
Console.WriteLine(string.Join(", ", strings.OrderBy(item => item, comp)));

Upvotes: 2

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23258

You can just use Ordinal string comparison

var strings = new[] { "asd", "ásd", "álm", "alm" };
Console.WriteLine(string.Join(", ", strings.OrderBy(item => item, StringComparer.Ordinal)));

It gives you

alm, asd, álm, ásd

Upvotes: 2

Related Questions