LINQ OrderBy is not sorting correctly

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? :)


Solution 1:

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:

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