2011-01-13 152 views
0

有沒有辦法在VB中對J10和J11之後的數組進行排序呢?在VB中對字符串數組進行排序的問題

J1 (PN= 605848)   
J10 (PN= 605987)   
J11 (PN= 605987)   
J2 (PN= 605848)   
J3 (PN= 605836)   
J4 (PN= 605848)   
J5 (PN= 605848)   
J6 (PN= 605848)   
J7 (PN= 605189)   
J7B (PN= 605189)   
J7E (PN= 605189)   
J7F (PN= 605189)   
J7I (PN= 605189)   
J7J (PN= 605189)   
J7M (PN= 605189)   
J7N (PN= 605189)   
J8 (PN= 605987)   
J9 (PN= 605987)  

這是我得到我運行myArray.sort()

謝謝你了。

+0

你沒有提到什麼VB版本。我想這是一些.NET版本。然後,您可以編寫自己的比較器來執行此自定義排序。 – MicSim 2011-01-14 11:02:46

回答

1

假設你正在使用某些版本VB.Net的:

MicSim是正確的,你需要使用自己的比較。以下是如何做到這一點。

比較器是任何類inherits Comparer(Of東西)。在你的情況下,它應該繼承比較器(字符串),因爲你想排序的值是字符串。

' If this class is frequently used, it should be in it's own source file. 
' If it's used only in one place, put it at the end of that source file. 

' This class is used to compare strings of the form L123 
' where L is a letter A-Z 
' and 123 is an integer 
' The goal here is to make sure that "L9" comes before "L10", 
' which isn't what we would get with simple string comparisons. 
Class CompLetterInteger 
    Inherits Comparer(Of String) 
    Public Overrides Function Compare(ByVal x As String, ByVal y As String) As Integer 
     ' Can value "Nothing" be in the array? 
     ' This makes sure that they come at the beginning of the array. 
     ' Skip these 8 lines if value Nothing is impossible. 
     If x Is Nothing Then 
      If y Is Nothing Then 
       Return 0 ' Values sort the same 
      End If 
      Return -1 ' X comes before Y 
     ElseIf y Is Nothing Then 
      Return 1 ' Y comes before X 
     End If 

     ' Here we parse both arguments into the first letter, 
     ' and then the numeric part. You might have to adjust 
     ' this for your data - if value "J123X" is possible, 
     ' you're going to have to adjust this. 
     Dim x1 As String = x.Substring(0, 1) 
     Dim x2 As Integer = 0 
     Integer.TryParse(x.Substring(1), x2) 

     Dim y1 As String = y.Substring(0, 1) 
     Dim y2 As Integer = 0 
     Integer.TryParse(y.Substring(1), y2) 

     ' Now decide which value should come first. 
     ' -1 means that X should come first, 
     ' +1 means that Y should come first, 
     ' 0 means that they sort the same. 
     If x1 < y1 Then Return -1 ' The letter of X is before the letter of Y 
     If x1 > y1 Then Return 1 ' The letter of X is after the letter of Y 
     ' The letters are equal, so look at the numeric part 
     If x2 < y2 Then Return -1 ' The number of X is less than the number of Y 
     If x2 > y2 Then Return 1 ' The number of X is more than the number of Y 
     Return 0 ' The two strings sort the same 
     ' Note that this does not mean that the two strings are identical. 
     ' "Y99" would sort the same as "Y099", 
     ' because the letters are the same and the numbers are the same value. 
    End Function 
End Class 

要真正對數組進行排序:

Dim Arr() As String = {"J1", "J9", "J10", "J11"} ' Etc. 
Array.Sort(Arr, New CompLetterInteger) 
相關問題