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


i have list, each element in list string contains date , 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 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: think every string(day_number) split underline, compare , sort number. please suggest me linq solution or better way sort in case.

since dates in format can ordered lexicographically, sort date prefix using string ordering, , resolve ties parsing integer:

var sorted = liststr     .orderby(s => s.split('_')[0])     .thenby(s => int.parse(s.split('_')[1])); 

demo.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -