c# - Alphanumeric sorting using LINQ -
i have string[]
in every elements ends numeric value.
string[] partnumbers = new string[] { "abc10", "abc1","abc2", "abc11","abc10", "ab1", "ab2", "ab11" };
i trying sort above array follows using linq
not getting expected result.
var result = partnumbers.orderby(x => x);
actual result:
ab1
ab11
ab2
abc1
abc10
abc10
abc11
abc2
expected result
ab1
ab2
ab11
..
that because default ordering string standard alpha numeric dictionary (lexicographic) ordering, , abc11 come before abc2 because ordering proceeds left right.
to want, need pad numeric portion in order clause, like:
var result = partnumbers.orderby(x => padnumbers(x));
where padnumbers
defined as:
public static string padnumbers(string input) { return regex.replace(input, "[0-9]+", match => match.value.padleft(10, '0')); }
this pads zeros number (or numbers) appear in input string orderby
sees:
abc0000000010 abc0000000001 ... ab0000000011
the padding happens on key used comparison. original strings (without padding) preserved in result.
note approach assumes maximum number of digits numbers in input.
Comments
Post a Comment