如何在 VB.NET 中搜索数组? [英] How can I search an array in VB.NET?
问题描述
我希望能够有效地在数组中搜索字符串的内容.
示例:
I want to be able to effectively search an array for the contents of a string.
Example:
dim arr() as string={"ravi","Kumar","Ravi","Ramesh"}
我传递的值为ra",我希望它返回 2 和 3 的索引.
I pass the value is "ra" and I want it to return the index of 2 and 3.
如何在 VB.NET 中执行此操作?
How can I do this in VB.NET?
推荐答案
不清楚您想如何搜索数组.以下是一些替代方案:
It's not exactly clear how you want to search the array. Here are some alternatives:
查找包含确切字符串Ra"的所有项目(返回项目 2 和 3):
Find all items containing the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.Contains("Ra"))
查找以字符串Ra"开头的所有项目(返回项目 2 和 3):
Find all items starting with the exact string "Ra" (returns items 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.StartsWith("Ra"))
查找包含任何大小写版本的ra"的所有项目(返回项目 0、2 和 3):
Find all items containing any case version of "ra" (returns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().Contains("ra"))
查找以任何大小写形式的ra"开头的所有项目(返回项目 0、2 和 3):
Find all items starting with any case version of "ra" (retuns items 0, 2 and 3):
Dim result As String() = Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))
-
如果您使用的不是 VB 9+,那么您就没有匿名函数,因此您必须创建一个命名函数.
If you are not using VB 9+ then you don't have anonymous functions, so you have to create a named function.
示例:
Function ContainsRa(s As String) As Boolean
Return s.Contains("Ra")
End Function
用法:
Dim result As String() = Array.FindAll(arr, ContainsRa)
拥有一个只能与特定字符串进行比较的函数并不总是很有用,因此为了能够指定一个字符串进行比较,您必须将它放在一个类中以便在某个地方存储字符串:
Having a function that only can compare to a specific string isn't always very useful, so to be able to specify a string to compare to you would have to put it in a class to have somewhere to store the string:
Public Class ArrayComparer
Private _compareTo As String
Public Sub New(compareTo As String)
_compareTo = compareTo
End Sub
Function Contains(s As String) As Boolean
Return s.Contains(_compareTo)
End Function
Function StartsWith(s As String) As Boolean
Return s.StartsWith(_compareTo)
End Function
End Class
用法:
Dim result As String() = Array.FindAll(arr, New ArrayComparer("Ra").Contains)
这篇关于如何在 VB.NET 中搜索数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!