Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how can I sort a list of file by index using linq

Tags:

c#

sorting

linq

Hello I need to sort all the files I have in a folder but I got stuck because I need to sort them by index. I'll give you an example:

My files are formatted like this: dateHoursMinutes_index_nameOfFile.dat

Previous I used Array.Sort(_myFiles); to sort them all but now I need to sort them by index, in order.

How can I use linq to do that?

Thank you

like image 647
sebba23 Avatar asked Dec 19 '25 12:12

sebba23


1 Answers

Please refer to the following sample code:

string[] _myFiles = new string[4]
{
    "dateHoursMinutes_4_nameOfFile",
    "dateHoursMinutes_1_nameOfFile",
    "dateHoursMinutes_3_nameOfFile",
    "dateHoursMinutes_2_nameOfFile"
};

char[] sep = new char[1] { '_' };
string[] sorted = _myFiles
    .OrderBy(x => Convert.ToInt32(x.Split(sep)[1]))
    .ToArray();
like image 123
mm8 Avatar answered Dec 22 '25 02:12

mm8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!