user6096423 user6096423 - 3 months ago 17
Vb.net 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:

10|100|1820160830
20|200|1820160831
30|300|1820160901


The current result is:

20|200|1820160831


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

20|200|1820160831-2





EDIT

I tried this solution:

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


but the result is always -1

Answer

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