The reason the order is "incorrect" is because the names are strings and therefore are ordered as strings. What you want is to order by the numeric part of it:
DirectoryInfo info = new DirectoryInfo("");
var files = info.GetFiles()
.OrderBy(p => p.FullName.Split('_')[0])
.ThenBy(p => int.Parse(p.FullName.Split('_')[1]));
If you are not sure the format is exactly like that (with a _
and then a valid number) then you can:
Func<string, int, int> parseIntOrDefault = (input, defaultValue) =>
{
int value = defaultValue;
int.TryParse(input, out value);
return value;
};
var result = from file in info.GetFiles()
let sections = file.FullName.Split('_')
orderby sections[0], sections.Length == 2 ?
parseIntOrDefault(sections[1], int.MaxValue) : int.MaxValue
select file;