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

4440|4420|4430|1720160906
4430|4410|4420|1820160906
4420|4400|4410|1920160906


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")))


and

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


and

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


but none of the above is working

Answer

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
    <Extension>
    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.