7

If I have a multidimensional array:

Dim test(,,) As String

How can I loop through the array to find if another variable is contained in the second dimension of the array?

Obviously, this won’t work:

Dim x As Integer = test.IndexOf(otherVariable)
0

4 Answers 4

3

You'll need to loop through the array using the Array.GetLowerBound and Array.GetUpperBound methods. The Array.IndexOf and Array.FindIndex methods don't support multidimensional arrays.

For example:

string[,,] data = new string[3,3,3];
data.SetValue("foo", 0, 1, 2 );

for (int i = data.GetLowerBound(0); i <= data.GetUpperBound(0); i++)
    for (int j = data.GetLowerBound(1); j <= data.GetUpperBound(1); j++)
        for (int k = data.GetLowerBound(2); k <= data.GetUpperBound(2); k++)
            Console.WriteLine("{0},{1},{2}: {3}", i, j, k, data[i,j,k]);

You might also find the Array.GetLength method and Array.Rank property useful. I recommend setting up a small multidimensional array and using all these methods and properties to get an idea of how they work.

Sign up to request clarification or add additional context in comments.

Comments

2

Have you tried LINQ? Perhaps something along the lines of (pseudo-code-ish):

var x = (from item in test
         where item.IndexOf(OtherVariable) >= 0 
         select item.IndexOf(OtherVariable)).SingleOrDefault();

FYI, this should work if you declare your array like this instead:

string[][] test

2 Comments

It's multidimensional so the Contains won't work since item itself is an array
Ok, then substitute Contains for array-friendly code (like I said, pseudo-code-ish). Instead of Contains, how about where item.IndexOf(OtherVariable) >= 0 ? I'll update my answer.
2

You'll need to do something similar to this..

Dim test As String(,) = New String(,) {{"1", "2", "3"}, {"4", "5", "6"}}

Dim cols As Integer = test.GetUpperBound(0)
Dim rows As Integer = test.GetUpperBound(1)

Dim toFind As String = "4"
Dim xIndex As Integer
Dim yIndex As Integer

For x As Integer = 0 To cols - 1
    For y As Integer = 0 To rows - 1
        If test(x, y) = toFind Then
            xIndex = x
            yIndex = y
        End If
    Next
Next

On a side note, a lot of people don't realise that you can use a for each loop on multi-dimension arrays.

For Each value As String In test
    Console.WriteLine(value)
Next

This will progressively loop through all dimensions of an array.

Hope this helps.

Comments

1

Similar to the previous question you asked

For i = 0 To i = test.Count - 1
   If set(1).Equals(someVariable) Then
      x = i
      Exit For
   End If
Next

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.