Find the index of an element in a multidimensional array

If I have a multidimensional array:

Dim test(,,) As String 

How can I go through an array to find if there is another variable in the second dimension of the array?

Obviously this does not work:

 Dim x As Integer = test.IndexOf(otherVariable) 
+6
c # multidimensional-array
source share
4 answers

Have you tried LINQ? Maybe something similar (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 instead declare your array as follows:

 string[][] test 
+2
source share

You will need to loop through the array using Array.GetLowerBound and Array.GetUpperBound . The methods Array.IndexOf and Array.FindIndex do not support multidimensional arrays.

For instance:

 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 can also find the Array.GetLength method and the Array.Rank property . I recommend setting up a small multidimensional array and using all of these methods and properties to get an idea of ​​how they work.

+3
source share

You will 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 the other hand, many people do not realize that you can use a for each loop on multidimensional arrays.

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

This will gradually go through all the sizes of the array.

Hope this helps.

+2
source share

As in 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 
+1
source share

All Articles