0

I want to sort it be the number of the names of each file. The array content is:

0Infrared.jpg
10Infrared.jpg
12Infrared.jpg
14Infrared.jpg
16Infrared.jpg
2Infrared.jpg
4Infrared.jpg
6Infrared.jpg
8Infrared.jpg

But i want it to be ordered like it is on the hard disk:

0Infrared.jpg
2Infrared.jpg
4Infrared.jpg
6Infrared.jpg
8Infrared.jpg
10Infrared.jpg
12Infrared.jpg
14Infrared.jpg
16Infrared.jpg

string[] list = Directory.GetFiles(countriesMainPath + "\\" + currentDownloadCountry,
             "*infrared*.jpg");
                            Array.Sort(list, (x, y) => String.Compare(x.Name, y.Name));

The variables x and y does not have the properties Name

  • 2
    If you have a fixed pattern `NNNInfrared.jpg` then you can remove the `Infrared.jpg` part and then parse to int and sort by that number. – Zein Makki Jan 14 '17 at 15:06

2 Answers2

1

You have to extract the number, parse it and sort the entire list by this number

string[] sorted = list.Select(x => new { 
           Item = x, 
           Number = int.Parse(Regex.Match(x, "[0-9]+").Value) })
               .OrderBy(x => x.Number).Select(x => x.Item).ToArray();

Note that this solution assumes that all files start with a number.

Flat Eric
  • 7,971
  • 9
  • 36
  • 45
1

You should use a strongly typed collection, like array of FileInfo, you could use DirectoryInfo.GetFiles or similar overload to retrieve such a collection

FileInfo has a name property which you can use in your comparer

The type of sorting that you're doing is called a natural sort

Community
  • 1
  • 1
ironstone13
  • 3,325
  • 18
  • 24