【问题标题】:VB.NET Find a string in an Array [duplicate]VB.NET 在数组中查找字符串 [重复]
【发布时间】:2013-05-23 12:05:18
【问题描述】:

我是 VB.net 的新手,通常是 Python 或 Matlab 程序员。我已经开始使用 VB.Net 进行编程。我正在努力引用数组中字符串的索引而不循环通过 for 循环

如何在一行中找到数组中的条目?我的想法是这样的。。

Dim indx As Integer
Dim MyArray() As String   

indx = MyArray.find("ThisEntry")

的索引
indx = MyArray.indexof("ThisEntry")

到目前为止,我发现的只是在声明变量后直接描述方法的函数?我错过了什么吗?还是逻辑没有意义?

【问题讨论】:

  • 总会有一个循环在某个地方,这只是你是否调用它或将功能卸载到另一个函数或方法的问题。
  • “到目前为止,我发现的只是在声明变量后直接描述方法的函数”是什么意思,抱歉,我无法解析该语句,您能澄清一下吗?
  • @YaugenVlasau:那是 C#,不是 VB .NET

标签: arrays vb.net


【解决方案1】:

这样做,在你的数组上有一些内容之后,现在是空的:

Dim result As String = Array.Find(MyArray, Function(s) s = "ThisEntry")

获取索引:

Dim index As Integer = Array.FindIndex(MyArray, Function(s) s = "ThisEntry")

【讨论】:

  • @CarlosLanderas 也许扩展方法并不适合初学者...
  • 是的,我更喜欢 C# 风格的一千倍,但是......
  • Array.FindIndex+1。
  • +1 在哪里? @Neolisk :P :P
  • @CarlosLanderas:抱歉,被其他事情分心了。固定。
【解决方案2】:

IndexOf 有效,只是你没有正确使用它。

Dim arr As String() = {"aa", "bb", "cc"}

index = Array.IndexOf(arr, "bb")

【讨论】:

    【解决方案3】:
    Dim MyArray() As String = {"a", "ThisEntry", "b"}
    Dim indx As Integer = MyArray.ToList().IndexOf("ThisEntry")
    

    【讨论】:

    • .ToList() 创建数组的副本,效率有点低。
    【解决方案4】:
    Sub Main()
        Dim numbers As String() = {"aaa", "bbb", "ccc"}
    
        Console.WriteLine(numbers.ToList().FindIndex(Function(x) x = "bbb"))
    End Sub
    

    【讨论】:

    • 你在哪里将“what”变量传递给 findbbb 函数?
    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 2015-08-13
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2018-10-18
    相关资源
    最近更新 更多