Natural Sort Order in C#

后端 未结 17 2091
野性不改
野性不改 2020-11-21 04:54

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

17条回答
  •  野的像风
    2020-11-21 05:33

    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).

提交回复
热议问题