Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c# - Alphanumeric sorting using LINQ

I have a string[] in which every elements ends with some numeric value.

string[] partNumbers = new string[] 
{ 
    "ABC10", "ABC1","ABC2", "ABC11","ABC10", "AB1", "AB2", "Ab11" 
};

I am trying to sort the above array as follows using LINQ but I am not getting the expected result.

var result = partNumbers.OrderBy(x => x);

Actual Result:

AB1
Ab11
AB2
ABC1
ABC10
ABC10
ABC11
ABC2

Expected Result

AB1
AB2
AB11
..

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is because the default ordering for string is standard alpha numeric dictionary (lexicographic) ordering, and ABC11 will come before ABC2 because ordering always proceeds from left to right.

To get what you want, you need to pad the numeric portion in your order by clause, something like:

 var result = partNumbers.OrderBy(x => PadNumbers(x));

where PadNumbers could be defined as:

public static string PadNumbers(string input)
{
    return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}

This pads zeros for any number (or numbers) that appear in the input string so that OrderBy sees:

ABC0000000010
ABC0000000001
...
AB0000000011

The padding only happens on the key used for comparison. The original strings (without padding) are preserved in the result.

Note that this approach assumes a maximum number of digits for numbers in the input.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...