Detail In the New subroutine we use IndexOf to search for the first space. We then parse the integer and store it. We also store the strings.
Detail In CompareTo, we have to compare two Line instances. We first compare the number stored on each object.
And This is the number we parsed in the New subroutine. If those are equal, we compare the remaining parts of the lines.
Implements IComparable(Of Line)
Dim _number As Integer
Dim _afterNumber As String
Public _line As String
Public Sub New(ByVal line As String)
' Here we parse the integer digits before the first space.
Dim firstSpace As Integer = line.IndexOf(" "c)
Dim digits As String = line.Substring(0, firstSpace)
' Store data in class fields.
_number = Integer.Parse(digits)
_afterNumber = line.Substring(firstSpace)
_line = line
Public Function CompareTo(other As Line) As Integer _
Implements IComparable(Of Line).CompareTo
' Compare first based on number at the start of the line.
' Then compare the string parts.
Dim result1 As Integer = _number.CompareTo(other._number)
If Not result1 = 0 Then
Dim lines As List(Of Line) = New List(Of Line)()
' Read lines in from this file.
Using reader As New StreamReader("C:\\programs\\p.txt")
Dim line As String = reader.ReadLine
If line = Nothing Then
' Sort lines based on IComparable.
' Display original lines in sorted order.For Each value As Line In lines
End Module2 - pa
2 - zo
3 - ad
3 - za
23 - zo
Code notes. In the Main Sub, we read in the text file. And we parse it by passing each line to the Line constructor. Finally we sort the lines List—this invokes the CompareTo Function.
So The lines are all sorted by their leading Integers, and then by their remaining characters.
Tip Often, this approach is superior to more complex methods that sort strings. We gain an object model of our data.
And The code here is less confusing than alternative approaches like the alphanumeric sorting methods I have developed.