Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a string array from any character position

Tags:

arrays

vb.net

Working with vb 2008 I need to sort an array of strings: (for example:)

dim list1() as String={"CONE0Z08TTTBALL","BARE0U04TTTBALL",  
             "APTN0S01TTTBALL","SPTN0K02TTTBALL"}

sorted from 5th character (not first):

  1. SPTN0K02TTTBALL
  2. VPTN0S01TTTBALL
  3. BARE0U04TTTBALL
  4. CONE0Z08TTTBALL

There is any way using the Array class sort?

like image 857
Spiromer Avatar asked Nov 24 '25 08:11

Spiromer


1 Answers

You can use linq to do that. I changed APTN0K02TTTBALL to SPTN0K02TTTBALL since that looks like a typo.

Dim list1() As String = {"CONE0Z08TTTBALL", "BARE0U04TTTBALL",
     "APTN0S01TTTBALL", "SPTN0K02TTTBALL"}
Dim result = list1.OrderBy(Function(q) q.Substring(5)).ToArray

For Each s As String In result
    Console.WriteLine(s)
Next

Output:

SPTN0K02TTTBALL
APTN0S01TTTBALL
BARE0U04TTTBALL
CONE0Z08TTTBALL

Note: If by 5th character, you meant 1-based, change the substring argument (which is 0 based) . Also, this is an alpha sort, so if you want to sort by the value of a numeral, you should also convert to integer. Not sure which you mean.

ryanyuyu kindly wrote you this DotNetFiddle

like image 177
Ňɏssa Pøngjǣrdenlarp Avatar answered Nov 26 '25 23:11

Ňɏssa Pøngjǣrdenlarp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!