C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Line: The Line class inherits from IComparable. It has a New method, where we parse the String data. And it implements CompareTo.
IComparableNew: 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.
CompareTo: 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.
Data file: p.txt
2 - pa
2 - zo
23 - zo
3 - ad
3 - za
VB.NET program that parses lines into objects
Imports System.IO
Class Line
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
End Sub
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
Return result1
End If
Return _afterNumber.CompareTo(other._afterNumber)
End Function
End Class
Module Module1
Sub Main()
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")
While True
Dim line As String = reader.ReadLine
If line = Nothing Then
Exit While
End If
lines.Add(New Line(line))
End While
End Using
' Sort lines based on IComparable.
lines.Sort()
' Display original lines in sorted order.
For Each value As Line In lines
Console.WriteLine(value._line)
Next
End Sub
End Module
Output
2 - pa
2 - zo
3 - ad
3 - za
23 - zo
So: The lines are all sorted by their leading Integers, and then by their remaining characters.
And: The code here is less confusing than alternative approaches like the alphanumeric sorting methods I have developed.
Alphanumeric Sort