Dudute Dudute - 1 year ago 95
C# Question

OrderBy with Swedish letters

I have a list of my custom class Customer and I want to sort them alphabetically by Title.
So I wrote

myList = myList.OrderByDescending(x => x.Title).ToList<Customer>();

Now the problem is that this method doesn't support the Swedish way of sorting the letters å, ä, ö. They should appear at the end after the letter z but they don't.

So I made a workaround method that replaces the Swedish letters before the ordering and then changes them back afterwords. It looks like this but it is quite slow. Can somebody think of a better way?

private List<Customer> OrderBySwedish(List<Customer> myList)
foreach (var customer in myList)
customer.Title = customer.Title.Replace("å", "zzz1").Replace("ä", "zzz2").Replace("ö", "zzz3").Replace("Å", "Zzz1").Replace("Ä", "Zzz2").Replace("Ö", "Zzz3");

myList= myList.OrderBy(x => x.Title).ToList<Customer>();

foreach (var customer in myList)
customer.Title = customer.Title.Replace("zzz1", "å").Replace("zzz2", "ä").Replace("zzz3", "ö").Replace("Zzz1", "Å").Replace("Zzz2", "Ä").Replace("Zzz3", "Ö");
return myList;

Answer Source

You can use culture specific StringComparer, see here.

CultureInfo culture = new CultureInfo("sv-SE");
var result = myList.OrderByDescending(x => 
               x.Title, StringComparer.Create(culture, false));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download