Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo
array? I am implementing the IComparer
interface in
Just thought I'd add to this (with the most concise solution I could find):
public static IOrderedEnumerable OrderByAlphaNumeric(this IEnumerable source, Func selector)
{
int max = source
.SelectMany(i => Regex.Matches(selector(i), @"\d+").Cast().Select(m => (int?)m.Value.Length))
.Max() ?? 0;
return source.OrderBy(i => Regex.Replace(selector(i), @"\d+", m => m.Value.PadLeft(max, '0')));
}
The above pads any numbers in the string to the max length of all numbers in all strings and uses the resulting string to sort.
The cast to (int?
) is to allow for collections of strings without any numbers (.Max()
on an empty enumerable throws an InvalidOperationException
).