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.

4

2 回答 2

1

这是使用 Framework 2.0 代码的一种方法,只需将 SearchString 设置为您要搜索的字符串:

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

当我用一个 87,000 行的文件进行测试时,填充列表框大约需要 0.5 秒。

于 2013-05-28T19:56:17.480 回答
1

我不是 VB 人,但我认为您可以使用 Linq:

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

查看: 如何使用 VB.NET 和 LINQ 附加“where”子句?

于 2013-05-28T15:12:41.567 回答