Sort Strings with Numberic and Text

Hi all

I've search the web for string sorting, and I've tried all the confentional ways of sorting. I need help in sorting a strings contraining numbers and text. Here is an example I did to see if SortedList won't work. The number will alway be infront of the letter.

string[] sArr = new string[] { "01A", "10A", "02A", "01B", "06B","22A","0A3" };

SortedList<string, string> sortedList = new SortedList<string, string>();

foreach(string s in sArr)

{

sortedList.Add(s, s);

}

foreach(KeyValuePair<string, string> kvp in sortedList)

{

Console.WriteLine(kvp.Value);

}

THE Rest comes out as

01A

01B

02A

03A

06B

10A

22A

WHERE IT SHOULD actaully be

01A

02A

03A

10A

22A

01B

06B



Answer this question

Sort Strings with Numberic and Text

  • ziad_dodin

    Thanks James.

    This should work perfect.


  • Andy McDonald

    Since you have special sorting needs, you will need to define a custom comparer, and you it to initialize the SortedList:

    SortedList<string, string> sortedList = new SortedList<string, string>(new NumberNumberLetter());

    The comparer itself is quite simple:

    // Warning: Untested code ahead.
    class NumberNumberLetter : IComparer<string>
    {
      public int Compare(string lhs, string rhs)
      {
        // Compare the letter
        int retv = lhs[2].CompareTo(rhs[2]);
        if (retv == 0)
          retv = lhs.CompareTo(rhs); // compare number
        return retv;
      }
    }


  • Sort Strings with Numberic and Text