Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get LINQ to order according to culture?

Tags:

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?

like image 493
Blixt Avatar asked Dec 04 '09 10:12

Blixt


People also ask

How do I order from LINQ?

LINQ includes five sorting operators: OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse. LINQ query syntax does not support OrderByDescending, ThenBy, ThenByDescending and Reverse. It only supports 'Order By' clause with 'ascending' and 'descending' sorting direction.

How do I use ascending order in LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.

How does OrderBy work in C#?

In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.

What algorithm does LINQ use?

For LINQ to Objects, it's a stable quicksort that is used.


1 Answers

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)); 
like image 51
Jon Skeet Avatar answered Sep 26 '22 23:09

Jon Skeet