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)
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.
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
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.
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
精彩评论