C# Sort files by natural number ordering in the name?

后端 未结 7 1113
刺人心
刺人心 2020-12-03 18:09

I have files in directory like that

0-0.jpeg
0-1.jpeg
0-5.jpeg
0-9.jpeg
0-10.jpeg
0-12.jpeg

....

when i loading files:



        
相关标签:
7条回答
  • 2020-12-03 18:59

    I know this might be late, but here is another solution which works perfectly

    FileInfo[] files = di.GetFiles().OrderBy(n => Regex.Replace(n.Name, @"\d+", n => n.Value.PadLeft(4, '0')));
    

    Using Regex replace in the OrderBy Clause:

    Regex.Replace(n.Name, @"\d+", n => n.Value.PadLeft(4, '0'))

    So what this does, it pads the numeric values in the file name with a length of 4 chars in each number:

    0-0.jpeg     ->   0000-0000.jpeg
    0-1.jpeg     ->   0000-0001.jpeg
    0-5.jpeg     ->   0000-0005.jpeg
    0-9.jpeg     ->   0000-0009.jpeg
    0-10.jpeg    ->   0000-0010.jpeg
    0-12.jpeg    ->   0000-0012.jpeg
    

    But this only happens in the OrderBy clause, it does not touch the original file name in any way. The order you will end up with in the array is the "human natural" order.

    0 讨论(0)
提交回复
热议问题