【发布时间】:2011-03-16 15:45:07
【问题描述】:
如果我有一个多维数组:
Dim test(,,) As String
如何遍历数组以查找数组的第二维中是否包含另一个变量?
显然,这是行不通的:
Dim x As Integer = test.IndexOf(otherVariable)
【问题讨论】:
标签: c# vb.net multidimensional-array
如果我有一个多维数组:
Dim test(,,) As String
如何遍历数组以查找数组的第二维中是否包含另一个变量?
显然,这是行不通的:
Dim x As Integer = test.IndexOf(otherVariable)
【问题讨论】:
标签: c# vb.net multidimensional-array
您需要使用Array.GetLowerBound 和Array.GetUpperBound 方法遍历数组。 Array.IndexOf 和 Array.FindIndex 方法不支持多维数组。
例如:
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]);
您可能还会发现Array.GetLength method 和Array.Rank property 很有用。我建议设置一个小的多维数组并使用所有这些方法和属性来了解它们的工作原理。
【讨论】:
您尝试过 LINQ 吗?也许类似于(伪代码):
var x = (from item in test
where item.IndexOf(OtherVariable) >= 0
select item.IndexOf(OtherVariable)).SingleOrDefault();
仅供参考,如果您像这样声明数组,这应该可以工作:
string[][] test
【讨论】:
你需要做类似的事情..
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
另一方面,很多人没有意识到您可以在多维数组上使用 for each 循环。
For Each value As String In test
Console.WriteLine(value)
Next
这将逐步循环遍历数组的所有维度。
希望这会有所帮助。
【讨论】:
与您之前提出的问题类似
For i = 0 To i = test.Count - 1
If set(1).Equals(someVariable) Then
x = i
Exit For
End If
Next
【讨论】: