user934820 user934820 - 1 year ago 93 Question

Search from a list of string() in VB.NET

I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:

Dim mylines() As String = IO.File.ReadAllLines(mypath)
If mylines.Contains("food") Then
MsgBox("Value Exist")
End If

But the problem is that I want to check if mylines() contains a line which starts with my value. I can get this value from a single line by mylines(0).StartsWith method. But how do I find a string from all the lines which is starting from some value, e.g. "mysearch" and then get that line number?

I am using a
loop to do so, but it is slow.

For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)

Constrained to code for .NET 2.0, please.

Answer Source

Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:

Imports System.IO
Public Class Form1
    Dim SearchString As String = ""
    Dim Test() As String = File.ReadAllLines("Test.txt")

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        SearchString = "Food"
    End Sub

    Private Function StartsWith(s As String) As Boolean
        Return s.StartsWith(SearchString)
    End Function

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim SubTest() As String = Array.FindAll(Test, AddressOf StartsWith)
    End Sub
End Class

When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.

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