andruszkow
andruszkow

Reputation: 43

Unexpected result in OrderBy

I stumbled upon this while running a test case set to order emails alphabeticly.

var test1 = new List<string>
{
    "ZZZ", "AAA", "BBB"
};

var result1 = test1.OrderBy(t => t).ToList();
// Expected: AAA, BBB, ZZZ
// Result: BBB, ZZZ, AAA

var test2 = new List<string>
{
    "ZK", "AB", "BA"
};

var result2 = test2.OrderBy(t => t).ToList();
// Expected: AB, BA, ZK
// Result: AB, BA, ZK

I get this behavior both in .Net 4.6.1 and .Net Core 1.0, 2.0 and 2.1.

Am I missing something here or is this indeed a weird bug?

Upvotes: 3

Views: 89

Answers (1)

Brian Hj&#248;llund
Brian Hj&#248;llund

Reputation: 88

This is due to the culture you are running it under

AA will be interpreted as Å in some cultures, and that is lexically after both Z and B

Use the overload that takes an IComparer<_> to override the behavior.

Upvotes: 5

Related Questions