Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting when name includes letters and numeric digits

I have following array

[0] = GB_22_T0001.jpg
[1] = GB_22_T0002.jpg
[2] = GB_22_T0003.jpg
[3] = GB_22_T0006.jpg
[4] = GB_22_T0007.jpg
[5] = GB_22_T0008.jpg
[6] = GB_22_T0009.jpg
[7] = GB_22_T00010.jpg
[8] = GB_22_T00011.jpg
[9] = GB_22_T00012.jpg
[10] = GB_22_T00013.jpg

I have put this items in a listbox and noticed that 'GB_22_T00010' comes straight after 'GB_22_T0001' instead of 'GB_22_T0002'

Seems to be a common issue with c# but cannot find a common answer to the problem.

I tried sorting the array with Array.sort(data) and also tried LinQ's OrderBy method but none of them helps.

Anyone with a solution?

like image 704
Sahil Avatar asked May 24 '13 16:05

Sahil


People also ask

What is alphanumeric sorting?

Sorting alpha numeric strings Any alpha numeric sort places the alpha in order, and then numbers in order by their first numeral, so 1300 will come before 140 which does not work well for lists like call numbers in libraries.

How do you sort a number with a letter prefix in Excel?

1. Select a blank cell beside the numbers with letter prefix or suffix, says Cell B2, type the formula =EXTRACTNUMBERS(A2,TRUE) (A2 is the cell of number with letter prefix or suffix) into it, and then drag this cell's AutoFill Handle to the range as you need. See screenshot: 2.


1 Answers

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

First, this extension method :

public static IEnumerable<string> AlphanumericSort(this IEnumerable<string> 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<string> test = new List<string>() { "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.

like image 153
Picsonald Avatar answered Oct 03 '22 15:10

Picsonald