Consider the following list of two string elements, sorting it with Sort() or ordering with linq .OrderBy() gives an unexpected result, a.1.10-a-
being the first element in the newly ordered list.
var list = new List<string>
{
"a.1.1-a-",
"a.1.10-a-",
};
list.Sort();
foreach(var l in list)
Console.WriteLine(l);
foreach(var l in list.OrderBy(x=>x))
Console.WriteLine(l);
Actual results:
a.1.10-a-
a.1.1-a-
------
a.1.10-a-
a.1.1-a-
However, removing the letter a
from each of the elements, the output changes to:
a.1.1--
a.1.10--
------
a.1.1--
a.1.10--
I've reproduced this in https://dotnetfiddle.net/NBF3Pf
But, copying the same code in https://try.dot.net/ gives the expected results with and without the letter a
included towards the end of the two strings.
I have tried casting each of the strings to a list of char then to list of ints. The two lists are identical until the 0
which has the ASCII code of 48 and the -
which has a ASCII code of 45.
48 is greater than 45, but still the sorting places the element a.1.10-a-
first.
EDIT: The same results are happening by using list.Sort(StringComparer.InvariantCulture);
Could anyone explain why this is happening?