1.4. Sort Results in a Culture-Sensitive Manner
Problem
You want to ensure that when you sort in a query, the sort order is for an applicationspecific culture that may not be the same as the current thread's current culture.
Solution
Use the overload of the OrderBy query operator, which accepts a custom comparer in order to specify the culture in which to perform comparisons:
// Create CultureInfo for Danish in Denmark.
CultureInfo danish = new CultureInfo("da-DK");
CultureStringComparer comparer = new CultureStringComparer(danish,CompareOptions.
None);
var query = names.OrderBy(n => n, comparer);Discussion
Handling localization issues such as sorting for a specific culture is a relatively trivial task in .NET if the current culture of the current thread is the culture you want to use. The framework classes that assist in handling culture issues in C# are accessed by including the System.Globalization namespace. This namespace would be included in order to make the code in the solution run. One example of not using the thread current culture would be in an application that needs to display a sorted list of words in Danish on a version of Windows XP that is set for U.S. English. The current thread in the application may have a CultureInfo for "en-US" and, by default, the sort order for OrderBy will use the current culture sort settings. To specify that this list should sort according to Danish rules, a bit of work is necessary in the form of a custom comparer:
CultureStringComparer comparer ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access