1

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 for loop to do so, but it is slow.

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

Constrained to code for .NET 2.0, please.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user934820
  • 1,162
  • 3
  • 17
  • 48

2 Answers2

1

I'm not a VB guy, but I think you could use Linq:

Dim mylines() As String = IO.File.ReadAllLines(mypath)
??? = mylines.Where(Function(s) s.StartWith("food")) //not sure of the return type

Check out: How do I append a 'where' clause using VB.NET and LINQ?

Community
  • 1
  • 1
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
  • Thanks for you help, but it is almost the same as I am using/. – user934820 May 28 '13 at 15:36
  • As in same speed issue, or you think the code is the same? Do you have to read it all in for some other reason, or could you scan on the inbound? Perhaps never pulling it all would be best? – DonBoitnott May 28 '13 at 15:43
  • I forgot to mention that I am working in .net framework 2.0 linq is not fully supported in 2.0 framework and I think is it is not supported by string() function. – user934820 May 28 '13 at 16:12
1

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)
        ListBox1.Items.AddRange(SubTest)
    End Sub
End Class

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

tinstaafl
  • 6,908
  • 2
  • 15
  • 22