Natural Sort Order in C#

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

    Inspired by Michael Parker's solution, here is an IComparer implementation that you can drop in to any of the linq ordering methods:

    private class NaturalStringComparer : IComparer
    {
        public int Compare(string left, string right)
        {
            int max = new[] { left, right }
                .SelectMany(x => Regex.Matches(x, @"\d+").Cast().Select(y => (int?)y.Value.Length))
                .Max() ?? 0;
    
            var leftPadded = Regex.Replace(left, @"\d+", m => m.Value.PadLeft(max, '0'));
            var rightPadded = Regex.Replace(right, @"\d+", m => m.Value.PadLeft(max, '0'));
    
            return string.Compare(leftPadded, rightPadded);
        }
    }
    

提交回复
热议问题