26

Let's say I've got a list of strings with Swedish words: banan, äpple, apelsin, druva.

Now I want to get this list sorted (keep in mind that this is a very simplified version of the real query):

var result = from f in fruits // The list mentioned above
             orderby f
             select f

This will give me: apelsin, äpple, banan, druva. However, according to the Swedish alphabet, I should get: apelsin, banan, druva, äpple

I tried changing System.Threading.Thread.CurrentThread.CurrentCulture to sv-SE but that didn't really seem to affect it at all. Do I have to write my own lambda function and use .OrderBy(...) or is there something else I can do to keep the LINQ intact?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Blixt
  • 49,547
  • 13
  • 120
  • 153
  • I know this is an old question AND that my comment is not exact on what you asked. I also had troubles with sorting data from database that came from Entity Framework through linq. I figured out, that I had a wrong collation set in my database. I changed it to danish and the sorting worked correct again. – Kenneth Bo Christensen Nov 03 '16 at 10:43

2 Answers2

52

You can't do this with a query expression, but you can do it with explicit dot notation:

var result = fruits.OrderBy(f => f, StringComparer.CurrentCulture);

That should do it, assuming the thread's current culture is correct. Alternatively:

CultureInfo culture = new CultureInfo("sv-SE");
var result = fruits.OrderBy(f => f, StringComparer.Create(culture, false));
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yup, I suspected as much... I'd just hoped there was a convenient way to keep using the simplified LINQ query =) – Blixt Dec 04 '09 at 10:59
3

I've tried your use case and it did provide valid results without a need to provide culture-specific comparer (both in .NET 3.5 and .NET 4.0):

    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("sv-SE");
    var fruits = new[] { "banan", "äpple", "apelsin", "druva" };
    var result = (from f in fruits orderby f select f).ToList();

    // outputs: apelsin, banan, druva, äpple
    string resultsJoined = string.Join(", ", result);
Konstantin
  • 3,817
  • 4
  • 29
  • 39