Sort
number stringsLines in a file contain several parts. We want to sort them based on an integer within the line. A VB.NET function can be built to sort on numbers in strings.
We can parse the lines into objects and then sort those objects with a CompareTo
Function. The sorting operation involves 2 separate steps.
First we see the data file used in the program. Please place it in an accessible location on your computer and then adjust the StreamReader
to access that location.
2 - pa 2 - zo 23 - zo 3 - ad 3 - za
Let us examine the example code. The Line class
inherits from IComparable
—it has a New method, where we parse the String
data. And it implements CompareTo
.
IndexOf
to search for the first space. We then parse the integer and store it. We also store the strings.CompareTo
, we have to compare two Line instances. We first compare the number stored on each object.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 Module2 - pa 2 - zo 3 - ad 3 - za 23 - zo
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.
A preliminary step before sorting data is sometimes needed. With this sample code, we create a simple object model from text lines. This enables more powerful sorting of the data.