Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ OrderBy is not sorting correctly

Tags:

c#

linq

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

like image 719
foamy Avatar asked Feb 09 '18 07:02

foamy


2 Answers

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();
like image 70
Ry- Avatar answered Oct 23 '22 19:10

Ry-


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();
like image 42
Kim Raaness Avatar answered Oct 23 '22 18:10

Kim Raaness