4

I am new to VB.net, usually a Python or Matlab programmer.I have begun programming in VB.Net. I am battling to reference an index of a string in an array without looping through a for loop

How can I find an entry in an array in one line? My thinking is this..

Dim indx As Integer
Dim MyArray() As String   

indx = MyArray.find("ThisEntry")

or the index of

indx = MyArray.indexof("ThisEntry")

So far all I have found is function describing a method directly after you declare the variable? Am I missing something? or does the logic not make sense?

4
  • 3
    There is always going to be a loop somewhere, its just a matter of whether you call it or offload the capability to another function or method. Commented May 23, 2013 at 12:08
  • 1
    What do you mean by "So far all I have found is function describing a method directly after you declare the variable" sorry but I can't parse that statement, could you clarify it? Commented May 23, 2013 at 12:09
  • 1
    stackoverflow.com/questions/1764970/… Commented May 23, 2013 at 12:09
  • @YaugenVlasau: That's C#, not VB .NET Commented May 23, 2013 at 12:11

4 Answers 4

15

Do it this way, after you have some content on your array, that now is empty:

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

To get the index:

Dim index As Integer = Array.FindIndex(MyArray, Function(s) s = "ThisEntry")
Sign up to request clarification or add additional context in comments.

5 Comments

@CarlosLanderas Maybe Extension methods are not really suitable for a beginner...
Yeah I prefer a thousand times C# style but....
Where is the +1? @Neolisk :P :P
@CarlosLanderas: Sorry, got distracted by something else. Fixed.
7

IndexOf works, you're just not using it correctly.

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

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

Comments

6
Dim MyArray() As String = {"a", "ThisEntry", "b"}
Dim indx As Integer = MyArray.ToList().IndexOf("ThisEntry")

1 Comment

.ToList() creates a copy of the array which is a bit inefficient.
2
Sub Main()
    Dim numbers As String() = {"aaa", "bbb", "ccc"}

    Console.WriteLine(numbers.ToList().FindIndex(Function(x) x = "bbb"))
End Sub

1 Comment

Where are you passing "what" variable to findbbb function?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.