LINQ OrderBy is not sorting correctly

C#Linq

C# Problem Overview


I hope someone can prove me wrong here :)

If I do this:

List<string> a = new List<string> { "b", "c", "a", "aa" };
var b = a.OrderBy(o => o).ToList();

I would expect the result of 'b' to be:

a
aa
b
c

Instead, the result I get is:

a
b
c
aa

How can I get OrderBy to do a "correct" alphabetical sort? Am I just plain wrong? :)

C# Solutions


Solution 1 - C#

You’re in the Danish culture, which treats aa as å and puts it after ø accordingly. You can pass a string comparer that acts differently to OrderBy to change that:

var b = a.OrderBy(o => o, StringComparer.InvariantCulture).ToList();

Solution 2 - C#

Most likely a cultural thing. You could try this:

List<string> a = new List<string> { "b", "c", "a", "aa" };
var b = a.OrderBy(o => o, StringComparer.InvariantCultureIgnoreCase).ToList();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfoamyView Question on Stackoverflow
Solution 1 - C#Ry-View Answer on Stackoverflow
Solution 2 - C#Kim RaanessView Answer on Stackoverflow