Oosutsuke Oosutsuke - 2 months ago 24
C# Question

C# - How to sort list string number by linq?

I have a list, each element in the list is a string that contains date and integer in specific format: yyyyMMdd_number.

List<string> listStr = new List<string> { "20170822_10", "20170821_1", "20170823_4", "20170821_10", "20170822_11", "20170822_5",
"20170822_2", "20170821_3", "20170823_6", "20170823_21", "20170823_20", "20170823_2"};


When use method
listStr.Sort();


Result as below:

20170821_1
20170821_10
20170821_3
20170822_10
20170822_11
20170822_2
20170822_5
20170823_2
20170823_20
20170823_21
20170823_4
20170823_6


Expected Output:

20170821_1
20170821_3
20170821_10
20170822_2
20170822_5
20170822_10
20170822_11
20170823_2
20170823_4
20170823_6
20170823_20
20170823_21


The way: i think every string(day_number) will split with an underline, then compare and sort by number.
But please suggest me LINQ solution or better way to sort in this case.

Answer Source

Since the dates are in the format that can be ordered lexicographically, you could sort by the date prefix using string ordering, and resolve ties by parsing the integer:

var sorted = listStr
    .OrderBy(s => s.Split('_')[0])
    .ThenBy(s => int.Parse(s.Split('_')[1]));

Demo.