Natural Sort Order in C#

后端 未结 17 1994
野性不改
野性不改 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:36

    Matthews Horsleys answer is the fastest method which doesn't change behaviour depending on which version of windows your program is running on. However, it can be even faster by creating the regex once, and using RegexOptions.Compiled. I also added the option of inserting a string comparer so you can ignore case if needed, and improved readability a bit.

        public static IEnumerable OrderByNatural(this IEnumerable items, Func selector, StringComparer stringComparer = null)
        {
            var regex = new Regex(@"\d+", RegexOptions.Compiled);
    
            int maxDigits = items
                          .SelectMany(i => regex.Matches(selector(i)).Cast().Select(digitChunk => (int?)digitChunk.Value.Length))
                          .Max() ?? 0;
    
            return items.OrderBy(i => regex.Replace(selector(i), match => match.Value.PadLeft(maxDigits, '0')), stringComparer ?? StringComparer.CurrentCulture);
        }
    

    Use by

    var sortedEmployees = employees.OrderByNatural(emp => emp.Name);
    

    This takes 450ms to sort 100,000 strings compared to 300ms for the default .net string comparison - pretty fast!

提交回复
热议问题