user6096423 user6096423 - 1 year ago 72 Question

Find String line number concurrently with locating the line in VB

I successfully use this code to get the text from the line I am looking for:

Dim lines = all_prices.Split({vbCrLf}, StringSplitOptions.None)
Dim match = lines.FirstOrDefault(Function(x) x.EndsWith("1820160831"))

The sample data is:


The current result is:


What I want is to append to the line found the line number where it is found, eg:



I tried this solution:

indexOfText = Array.FindIndex(lines, Function(str) str.IndexOf("1820160831", StringComparison.InvariantCultureIgnoreCase) >= 0)

but the result is always -1

Answer Source

Give this a try, returns the index of the first match and appends the index to the string...

Dim all_prices As String = "10|100|1820160830" & vbCrLf & "20|200|1820160831" & vbCrLf & "30|300|1820160901"
Dim lines() As String = all_prices.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
Dim i As Integer = Enumerable.Range(0, lines.Count).Where(Function(x) lines(x).EndsWith("1820160831")).First
lines(i) = lines(i) & "-" & i.ToString 

"(i+1).ToString" on the last line instead of "i" if you want the line-number rather than the index

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download