In your case (a letter followed with numbers), you may require number padding like this (credits to Nathan):
public static string PadNumbers(string input)
{
// replace number "2" into number of digits you want to group with
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(2, '0'));
}
This way enables padding on numeric portion in OrderBy
clause, which should be used like this:
var naturalOrder = list.OrderBy(x => PadNumbers(x));
By using padding regex above, OrderBy
will see the number part like this:
a 01
a 20
a 02
a 12
a 25
...
and then ordering them like this:
a 01
a 02
a 12
a 20
a 25
...
Of course, the padding only used in comparison when deciding number orders and the original strings still preserved.
The reason behind padding usage is the default ordering used with OrderBy
in lexicographical order which process characters in string from left to right.
Working example: NET Fiddle Demo
Similar issue:
Alphanumeric sorting using LINQ