【问题标题】:Search from a list of string() in VB.NET从 VB.NET 中的 string() 列表中搜索
【发布时间】:2013-05-28 15:06:08
【问题描述】:

我正在尝试查找 mylines() 是否包含值。我可以通过 mylines.Contains 方法获取值:

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

但问题是我想检查 mylines() 是否包含以我的值开头的行。我可以通过 mylines(0).StartsWith 方法从一行中获取此值。但是我如何从所有从某个值开始的行中找到一个字符串,例如"mysearch" 然后得到那个行号?

我正在使用for 循环来执行此操作,但速度很慢。

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

请限制为 .NET 2.0 的代码。

【问题讨论】:

  • 你有多少行是慢的?
  • 不在编译器附近,但我相信mylines.IndexOf(line) + 1 会给出包含匹配字符串的行号。
  • 暂时是8.7万行,但随着时间的推移会增加。
  • mylines.IndexOf(line) + 1,对不起,我不明白你。有没有活生生的例子?
  • 您是否在寻求一种方法来获取以您的搜索字符串开头的所有行?

标签: vb.net string find .net-2.0


【解决方案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 秒。

【讨论】:

  • 它比我正在做的要慢。好的,离开它
【解决方案2】:

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

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

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

【讨论】:

  • 谢谢你的帮助,不过和我用的差不多/.
  • 同速问题,或者你认为代码是一样的?您是否必须出于其他原因将其全部阅读,或者您可以在入站时扫描吗?也许永远不要全力以赴是最好的?
  • 我忘了说我在 .net framework 2.0 中工作 linq 在 2.0 框架中不完全支持,我认为它不受 string() 函数的支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
相关资源
最近更新 更多