Implement a custom comparer class to sort alphanumeric entries in collection
Yesterday somebody asked a question in newsgroup about sorting of alphanumeric
collection. What it meant was that
page1.aspx, page3.aspx, page10.aspx, page12.aspx, page21.aspx, page2.aspx
ArrayList has following
Now if you use a simple sorting on this list, you will end up with the
page1.aspx, page10.aspx, page12.aspx, page2.aspx, page21.aspx, page3.aspx
This is not the type of sorting this developer was looking for. He wanted the
list sorted so that results look as follows.
page1.aspx, page2.aspx, page3.aspx, page10.aspx, page12.aspx, page21.aspx
Now this is a situation where simple sorting on the string type data will not work. This is where we had to implement our
own comparer class. The
Compare method uses the following regular expression to capture different groups
in it and then do an individual compare on them to get to final result of comparison.
String strPattern = @"^(?<1>\D*)(?<2>\d+)(?<3>\D*)*";
Regex regEx = new Regex(strPattern, RegexOptions.IgnoreCase);
Match m = regEx.Match(strVal);
By using this approach I was able to come up with a solution which works very well under the assumption that the string will
always be in the following format.
This solution will not work properly if you have numeric and text mixed all over the place.