Reputation: 361
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
Upvotes: 0
Views: 313
Reputation: 1275
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
Upvotes: 3