通过瑞典字母订购

问题描述:

我有一个自定义类Customer的列表,我想按Title的字母顺序对它们进行排序. 所以我写了

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>();

现在的问题是,此方法不支持瑞典语对字母å,ä,ö进行排序的方式.它们应该出现在字母z的末尾,但不是.

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;
    }

您可以使用特定于文化的StringComparer,请参见

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));