How can I use this code?
TextBox1.Text = Array.FindIndex(linestring, Function(s) s.Contains(something))
but to use the code, without a word, and to display my array index following the code below:
Dim lines As New List(Of String)
Using reader As New StreamReader(My.Application.Info.DirectoryPath ("\Data.txt"))
Dim line As String
Do Until line.StartsWith(endPrefix)
lines.Add(line)
line = reader.ReadLine()
'maybe here index of array
Loop
so how do I use this to get the line index from my text files?
CodePudding user response:
Here is an example which uses the File.ReadLines method (which enumerates the lines of a file) where you can pass the predicate for the comparison to get the line number (starting at 1) of the first match:
Imports System.IO
Module Module1
Function FindLineNumber(sourceFile As String, textToFind As String, predicate As Func(Of String, String, Boolean)) As Integer
Dim lineNo = 1
For Each l In File.ReadLines(sourceFile)
If predicate(l, textToFind) Then
Return lineNo
End If
lineNo = 1
Next
Return -1
End Function
Sub Main()
' File to look in:
Dim src = "C:\temp\population.csv"
' Text to find:
Dim find = "133"
Dim lineNum = FindLineNumber(src, find, Function(a, b) a.Contains(b))
If lineNum > 0 Then
Console.WriteLine($"""{find}"" found at line {lineNum}.")
Else
Console.WriteLine($"""{find}"" not found.")
End If
Console.ReadLine()
End Sub
End Module