user6096423 user6096423 - 4 months ago 25 Question

locate and extract line containing specific text in a multiline string in VB

I have data that comes in from the server that builds a string ('all_prices') held in memory that looks like this:


I want to locate the line that contains "1820160906" and isolate that as its own variable.

In search of the lightest amount of code possible, I tried:

MsgBox(File.ReadAllLines(all_prices).FirstOrDefault(Function(x) x.Contains("1820160906")))


all_prices(Of String).FirstOrDefault(Function(x) x.Contains("1820160906"))


all_prices.FirstOrDefault(Function(x) x.Contains("1820160906"))

but none of the above is working


You need to split the data into lines before using FirstOrDefault to find the matching line.

Dim lines = all_prices.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
Dim match = lines.FirstOrDefault(Function(x) x.Contains("1820160906"))

If you wanted a one-liner (ignoring the lines of the extension method :-), you could create an extension method and use that:

Module StringExtensions
    Public Iterator Function ReadLines(input As String) As IEnumerable(Of String)
        Using r = New StringReader(input)
            Dim line = r.ReadLine()
            While line IsNot Nothing
                Yield line
                line = r.ReadLine()
            End While
        End Using
    End Function
End Module

Dim match = all_prices.ReadLines().FirstOrDefault(Function(x) x.Contains("1820160906"))

Also, using EndsWith instead of Contains would be more efficient.