如何搜索在VB.NET数组? [英] How can I search an array in VB.NET?

查看:224
本文介绍了如何搜索在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的情况下,任何版本的所有项目(返回2项0,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的任何情况下,版本中的所有项目(retuns 2项0,和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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆