2013-01-02 35 views
1

我對使用字符串數組完全陌生。考慮下面這個例子:如何自定義字符串的排序順序

我有一個文本框中輸入以下值:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

當我對它們進行排序,他們是按字母順序排序,如在上面的列表中。不過,我需要它們使用@符號後面的整數值以降序排序。所以,舉例來說,我想上面的列表,以這樣的排序:

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

我對如何在他們那樣的遞減順序排列不知道。

+2

用於排序的正則表達式? – Oded

+0

任何事情都應該很好 – atari400

+0

您首先需要解釋排序規則。 – Oded

回答

1

您想按字符串的數字部分進行排序嗎?不需要Regex。

您可以使用String.SplitEnumerable.OrderByDescending

Dim number As Int32 = Int32.MinValue 
Dim orderedLines = From line In TextBox1.Lines 
        Let parts = line.Split("@"c) 
        Let numericPart = parts.Last() 
        Let success = Int32.TryParse(numericPart, number) 
        Select LineInfo = New With {line, number} 
        Order By LineInfo.number Descending 
        Select LineInfo.line 
' if you want to reassign it to the TextBox: 
TextBox1.Lines = orderedLines.ToArray() 
+0

謝謝這位先生,這真的有幫助,我可以從哪裏開始學習int32 – atari400

+0

'Int32'只是'Integer'類型。 ['Int32.TryParse'](http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx)正如名稱所暗示的:一種嘗試將字符串解析爲整數的方法。請注意,這是一個'Linq'查詢。所以你可能想學習:http://msdn.microsoft.com/en-us/library/vstudio/bb397906.aspx –

2

雖然這樣做在一個單一的LINQ表達你所有的邏輯可以證明,有時代碼是如何聰明你:)只是更容易閱讀和遵守,如果你這樣做以更詳細的方式。所以,如果你不想使用LINQ,你可以創建自己的IComparer類,其中包含您的自定義排序算法:

Public Class MyComparer 
    Implements IComparer(Of String) 

    Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements IComparer(Of String).Compare 
     Dim xParts() As String = x.Split("@"c) 
     Dim yParts() As String = y.Split("@"c) 

     'Get the integer value (after the @ symbol) of each parameter 
     Dim xValue As Integer = 0 
     Dim yValue As Integer = 0 
     If xParts.Length = 2 Then 
      Integer.TryParse(xParts(1), xValue) 
     End If 
     If yParts.Length = 2 Then 
      Integer.TryParse(yParts(1), yValue) 
     End If 

     'Compare y-to-x instead of x-to-y because we want descending order 
     Return yValue.CompareTo(xValue) 
    End Function 
End Class 

在這個例子中,IComparer是一個標準的.NET框架接口,它要實現在你的MyComparer班。 Compare方法(由IComparer定義)只需要兩個參數並對它們進行比較。如果x小於y(即x以排列順序在y之前),則該方法將返回負數(例如-1)。如果x大於y,它將返回一個正數(例如1)。如果xy相等,則該方法將返回0。

在這種情況下,然而,因爲所有我們要做的是使用標準的整數排序,我們可以叫Integer.CompareTo其中比較兩個整數並返回視情況而定,爲負數,正數或零。

然後,當你調用Array.Sort方法,你可以給它一個自定義的IComparer對象,以便它使用您的自定義排序,而不是默認的行爲算法:

Dim arrayToSort() As String = New String() {"[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"} 
Array.Sort(arrayToSort, New MyComparer()) 

Sort方法將使用IComparer您給它執行排序的對象。每次需要比較數組中的兩個項目以查看哪個應該先到達時,它將調用MyComparer.Compare並使用該方法返回的值來確定正確的排序。

您可以在代碼中隨處重複使用相同的MyComparer類,您需要使用相同的算法對項目進行排序,這與LINQ方法相比具有另一個優勢。實現你自己的IComparer類允許你做出各種非常強大的可定製的排序順序。

+0

首先,感謝精心設計,高度詳細的答案。這真的幫助我,我不能夠感謝你:) – atari400

+0

沒問題。樂意效勞! –