Codehelp
Codehelp

Reputation: 4747

Sorting a string based array on two conditions

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.

Upvotes: 2

Views: 593

Answers (2)

Ian Newson
Ian Newson

Reputation: 7949

    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.

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

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"

Upvotes: 5

Related Questions