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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With