Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of item in a multidimensional array

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)
like image 395
William Avatar asked Mar 16 '11 15:03

William


2 Answers

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.

like image 164
Ahmad Mageed Avatar answered Sep 16 '22 18:09

Ahmad Mageed


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
like image 21
Kon Avatar answered Sep 17 '22 18:09

Kon