Sort List using Filename

309 views Asked by At

i have a program where i need to list the files in my Listbox like the way windows Sort the files

i have this code

but it doesn't sort the Files properly

public ObservableCollection<string> FileNames { get; } = new ObservableCollection<string>();
    var lstfiles = System.IO.Directory.GetFiles(SelectedPath, "*").Select(fn => new FileInfo(fn)).OrderBy(f => f.Name);
                foreach (var item in lstfiles)
                {
                    FileNames.Add(item.ToString());
                }

my filenames are integer

1.pdf
2.pdf
3.pdf
4.pdf
...
4000.pdf

the program sort it this way

1.pdf
99.pdf
143.pdf
1

There are 1 answers

0
Hakunamatata On BEST ANSWER

You can sort list using digits in file name like below.

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

fiddler : https://dotnetfiddle.net/RHzdm2