从 VB.NET 中的 string() 列表中搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16795417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search from a list of string() in VB.NET
提问by user934820
I am trying to find if mylines() contains a value or not. I can get the value by mylines.Contains method:
我试图找出 mylines() 是否包含一个值。我可以通过 mylines.Contains 方法获取值:
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?
但问题是我想检查 mylines() 是否包含以我的值开头的行。我可以通过 mylines(0).StartsWith 方法从一行中获取这个值。但是如何从所有从某个值开始的行中找到一个字符串,例如“mysearch”,然后获取该行号?
I am using a forloop to do so, but it is slow.
我正在使用for循环来执行此操作,但速度很慢。
For Each line In mylines
If line.StartsWith("food") Then MsgBox(line)
Next
Constrained to code for .NET 2.0, please.
请限制为 .NET 2.0 的代码。
采纳答案by tinstaafl
Here's one way with Framework 2.0 code, simply set SearchString with the the string you want to search for:
这是使用 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
When I test this with a file with 87,000 lines, it takes about .5 sec, to fill the listbox.
当我用 87,000 行的文件对此进行测试时,填充列表框大约需要 0.5 秒。
回答by DonBoitnott
I'm not a VB guy, but I think you could use Linq:
我不是 VB 人,但我认为您可以使用 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?

