Natural Sort Order in C#

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

    This is my code to sort a string having both alpha and numeric characters.

    First, this extension method:

    public static IEnumerable AlphanumericSort(this IEnumerable me)
    {
        return me.OrderBy(x => Regex.Replace(x, @"\d+", m => m.Value.PadLeft(50, '0')));
    }
    

    Then, simply use it anywhere in your code like this:

    List test = new List() { "The 1st", "The 12th", "The 2nd" };
    test = test.AlphanumericSort();
    

    How does it works ? By replaceing with zeros:

      Original  | Regex Replace |      The      |   Returned
        List    | Apply PadLeft |    Sorting    |     List
                |               |               |
     "The 1st"  |  "The 001st"  |  "The 001st"  |  "The 1st"
     "The 12th" |  "The 012th"  |  "The 002nd"  |  "The 2nd"
     "The 2nd"  |  "The 002nd"  |  "The 012th"  |  "The 12th"
    

    Works with multiples numbers:

     Alphabetical Sorting | Alphanumeric Sorting
                          |
     "Page 21, Line 42"   | "Page 3, Line 7"
     "Page 21, Line 5"    | "Page 3, Line 32"
     "Page 3, Line 32"    | "Page 21, Line 5"
     "Page 3, Line 7"     | "Page 21, Line 42"
    

    Hope that's will help.

提交回复
热议问题