Spiromer
Spiromer

Reputation: 35

Sorting a string array from any character position

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?

Upvotes: 3

Views: 640

Answers (1)

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

Upvotes: 3

Related Questions