Search code examples
c#sortingstringcomparer

List<string> C# custom sorting. Underscore after digits


I have a list: "a_a", "a1a", "aaa".

I need to sort it in following way: "a1a", "a_a", "aaa".

In other words I need '_' symbols to appear right after digits but before letters.

I know it is possible to use custom Comparer, but I haven't found any nice solution for this issue, only dirty hacks, for example:

Compare(string x, string y){

return Comparer.Default.Compare(x.Replace("_", "9z"), y.Replace("_", "9z"));

}

Solution

  • According to standard ASCII table:

      '0'..'9' have codes 0x30..0x39
      '_'      -/-        0x5F
      'a'..'z' -/-        0x61..0x7A
    

    so since codes are in right order, you can use ordinal comparison:

      List<String> list = new List<string> {
        "a1a", "a_a", "aaa"
      };
    
      list.Sort((Comparison<String>) (
        (String left, String right) => {
           return String.CompareOrdinal(left, right);
        }
      ));
    
      ...
      // a1a, a_a, aaa
      Console.Write(String.Join(", ", list));