sebba23
sebba23

Reputation: 574

C# how can I sort a list of file by index using 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

Upvotes: 3

Views: 537

Answers (2)

Lucifer
Lucifer

Reputation: 1600

Try using Substring of _index_ from main string to do so

Lst<string> fileNames = new List<string>();

var SortedFiles = FileNames.OrderBy(x => Decimal.Parse(path.Substring(path.IndexOf("_") + 1, path.Substring(path.IndexOf("_") + 1).IndexOf("_"))).ToList();

Edit: to sort file name such as \\Programs\\Drop_99\\recepes\\CLF\\20180626113520_2_WAVES.dat use Path.GetFileName()

Solution using below answer as ref.

 var sampl12836 = xspli.OrderBy(ele =>
 {
    var path = Path.GetFileName(ele);
    return Decimal.Parse(path.Split('_')[1]); 
 }).ToList();

Solution using my answer:-

var sorted = FileNames.OrderBy(ele =>
{
    var path = Path.GetFileName(ele);
    int firstIndex = path.IndexOf("_");
    return Decimal.Parse(path.Substring(path.IndexOf("_") + 1, path.Substring(firstIndex + 1).IndexOf("_"))); 
}).ToList();

Upvotes: 3

mm8
mm8

Reputation: 169390

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();

Upvotes: 5

Related Questions