Pages

Thursday 2 February 2012

SortableStringValue

We have a number of different alphanumeric codes in our application that occasionally need to be sorted. Using the standard sorting mechanism we typically end up with a list that looks like this:
A1
A10
A2
A20
A3
A4

Paul has written an extension method that allows us to sort into alpha then numeric order, like this:
A1
A2
A3
A4
A10
A20

The extension method is used like this:
    var result = list.OrderBy(l => l.SortableStringValue())


public static class Extensions
{
   public static String SortableStringValue(this String text)
   {
      StringBuilder  textBuilder;
      StringBuilder  numberBuilder;
      textBuilder = new StringBuilder();
      numberBuilder = new StringBuilder();
      //Look at each char in the string
      foreach(char value in text)
      {
         switch (value)
         {
            //If its a number add it to the number builder
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
               numberBuilder.Append(value);
               break;
            //Else add it to the text builder
            default:             
               //Before we add the text, format and add any number we may have
               if (numberBuilder.Length > 0)
               {
                  textBuilder.Append(numberBuilder.ToString().PadLeft(16,'0'));
                  numberBuilder.Clear();
               }
               textBuilder.Append(value);
                  
               break;
         }
      }

      //Check to see if we have any numbers left in the builder
      if (numberBuilder.Length > 0)
      {
         textBuilder.Append(numberBuilder.ToString().PadLeft(16,'0'));
      }
      //Return the string value (The replace will allow negative number to be sorted)
      return textBuilder.ToString().Replace("-0","-00");
   }
}

No comments: