OrderBy with Swedish letters
Asked Answered
R

4

14

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;
    }
Resuscitate answered 29/8, 2011 at 11:26 Comment(0)
M
28

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));
Manfred answered 29/8, 2011 at 11:30 Comment(0)
K
4

Set the Thread.CurrentCulture property to the correct culture.

Kyl answered 29/8, 2011 at 11:32 Comment(0)
B
1

I my case: _My sorting list have value was encoded. This make my order incorrect. Add decoded solving my problems !

Bogy answered 21/10, 2016 at 4:6 Comment(0)
B
0

The workaround I found for a somewhat similar problem was to have a secondary field that held the converted version of the data.
In my case, we had person.Name and person.SearchName, where SearchName was Name converted to have no diacritics.

But this was only the best approach (AFAIK) because we wanted a speedy db search/filtering and then instantiating only the relevant results.
If you already have the objects in memory I would advise going with one of the other approaches; and not this one.

Bricklayer answered 29/8, 2011 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.