3

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

1

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

8 Comments

nice answer sir never have thought of it
If your file format is strict enough that it will always have the character _ as the first instance prior to your order index that you are interested in this will work very nicely
I think index should be ordered by int rather than string. So that it would be 1,2,3,10 rather than 1,10,2,3
@Mark: Good catch. I modified the solution slightly by converting the string to an int.
and what if I have this format "\\Programs\\Drop_99\\recepes\\CLF\\20180626113520_2_WAVES.dat" ?
|
3

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

1 Comment

and what if I have this format "\\Programs\\Drop_99\\recepes\\CLF\\20180626113520_2_WAVES.dat" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.