0

I try to sort a list that contains filepaths. And I want them to be sorted by the numbers in them.

With the given code I use I don't get the expected result.

var mylist = mylist.OrderBy(x => int.Parse(Regex.Replace(x, "[^0-9]+", "0"))).ToList<string>();

I expect the result to be:

c:\somedir\1.jpg
c:\somedir\2.jpg
c:\somedir\3.jpg
c:\somedir\7.jpg
c:\somedir\8.jpg
c:\somedir\9.jpg
c:\somedir\10.jpg
c:\somedir\12.jpg
c:\somedir\20.jpg

But the output is random.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
Oscar vs
  • 376
  • 2
  • 4
  • 17

2 Answers2

4

There is a simple way of achieving that. Let's say you have a string list like this:

List<string> allThePaths = new List<string>()
{
    "c:\\somedir\\1.jpg",
    "c:\\somedir\\2.jpg",
    "c:\\somedir\\20.jpg",
    "c:\\somedir\\7.jpg",
    "c:\\somedir\\12.jpg",
    "c:\\somedir\\8.jpg",
    "c:\\somedir\\9.jpg",
    "c:\\somedir\\3.jpg",
    "c:\\somedir\\10.jpg"
};

You can get the desired result with this:

List<string> sortedPaths = allThePaths
    .OrderBy(stringItem => stringItem.Length)
    .ThenBy(stringItem => stringItem).ToList();

Note: Also make sure you've included LINQ:

using System.Linq;

Here is a demo example just in case it's needed.

More complex solutions can be found there.

Just Shadow
  • 10,860
  • 6
  • 57
  • 75
  • 1
    In this case `8.jpg` will come before `01.jpg`. may work here but in general there is a chance to fail. – roozbeh S Jun 16 '19 at 18:52
  • 1
    Agreed, there is a chance. But I guess in that case `8.jpg` will instead be named `08.jpg` ;). Anyway, I've added a link to the answer for more complex solutions. – Just Shadow Jun 16 '19 at 19:00
0

A cleaner way of doing this would be to use System.IO.Path:

public IEnumerable<string> OrderFilesByNumberedName(IEnumerable<string> unsortedPathList) =>
    unsortedPathList
    .Select(path => new { name = Path.GetFileNameWithoutExtension(path), path }) // Get filename
    .OrderBy(file => int.Parse(file.name)) // Sort by number
    .Select(file => file.path); // Return only path
blenderfreaky
  • 738
  • 7
  • 26