2

I have an array of strings like so

May#01
April#02
Jan#03

I need to sort this first alphabetically and then by the numeric value next to the #. Alphabetical sort is obvious but I don't seem to get the numeric part.

2 Answers 2

5

First order strings by their values (that will give you alphabetic sort). Then filter by integer value which is after # character:

array.OrderBy(s => s)
     .ThenBy(s => Int32.Parse(s.Split('#')[1]))

Sample:

string[] array = { "May#01", "April#02", "Jan#03", "April#01" };
var query = array.OrderBy(s => s)
                 .ThenBy(s => Int32.Parse(s.Split('#')[1]));

Result:

"April#01"
"April#02"
"Jan#03"
"May#01"
Sign up to request clarification or add additional context in comments.

Comments

1
    var input = new[] { "May#01", "April#02", "Jan#03", "Jan#02", "Jan#1" };
    var result = input.OrderBy(s => s.Split('#')[0])
        .ThenBy(s => Int32.Parse(s.Split('#')[1]));

Result:

[
"April#02",
"Jan#1",
"Jan#02",
"Jan#03",
"May#01"
]

The other answer will produce the output:

[
"April#02",
"Jan#02",
"Jan#03",
"Jan#1",
"May#01"
]

Which I'm assuming is incorrect as Jan#02 comes before Jan#1.

You could make my code more efficient by doing the split once and storing both parts in an anonymous class, along with the original string, but I don't want to convolute the code.

2 Comments

Yup that worked, thanks Ian, one last thing how do I get all months as comma separated string as a final string.
@Codehelp you can use the same Split method, along with Select and string.Join

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.