Yanshof
Yanshof

Reputation: 9926

How to sort collection that contain string that represent file name?

I have some folder that contain 500 files. Each file name is a int => that mean that each file name is for example 1.txt or 40.txt

On my code i load all those file name into array

string[] allFiles = Directory.GetFiles(folderPath, "*.txt");

and now i need to do a sort on the files in the way that the file name is the sorted key ( 1.txt )

How to do it ?

Upvotes: 2

Views: 227

Answers (3)

Meligy
Meligy

Reputation: 36594

The directory API has sorting, but if this is not handling strings right (meaning "1.txt" is followed by "10.txt" not "2.txt"), you can try this:

  string[] allFiles = Directory.GetFiles(folderPath, "*.txt")
                          .OrderBy(file => 
                                int.Parse(file.Substring(0, file.Length - 4)))
                          .ToArray();

This assumes all the files are in correct format. If this is questionable, maybe you want something like that:

  string[] allFiles = Directory.GetFiles(folderPath, "*.txt")
                          .Select(file => {
                             var fileNamber;
                             if(!int.TryParse(
                                 file.Substring(0, file.Length - 4), out fileNamber)
                                 return (int?)null;
                             return (int?)fileNamber;
                          })
                          .Where(fileNamber => fileNamber.HasValue)
                          .OrderBy(fileNamber => fileNamber.Value)
                          .Select(fileNamber => fileNamber.Value + ".txt")
                          .ToArray();

Upvotes: 2

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

If you are sure that there are always exactly 500 files, and they are named from 1.txt to 500.txt, then you can simply generate the array manually, instead of scanning the directory:

string[] allFiles = Enumerable
                      .Range(1, 500)
                      .Select(i => Path.Combine(folderPath, $"{i}.txt"))
                      .ToArray();

Otherwise, parse filename without extension to int to sort it:

string[] allFiles = Directory
                      .GetFiles(folderPath, "*.txt")
                      .OrderBy(x => int.Parse(x.Substring(0, x.Length - 4)))
                      .ToArray();

Upvotes: 1

AnjumSKhan
AnjumSKhan

Reputation: 9827

var result = allFiles.OrderBy(f => Int32.Parse(f.Split(new char[] { '.' })[0]));

Upvotes: 1

Related Questions