【问题标题】:Find index of item in a multidimensional array在多维数组中查找项目的索引
【发布时间】:2011-03-16 15:45:07
【问题描述】:

如果我有一个多维数组:

Dim test(,,) As String

如何遍历数组以查找数组的第二维中是否包含另一个变量?

显然,这是行不通的:

Dim x As Integer = test.IndexOf(otherVariable)

【问题讨论】:

    标签: c# vb.net multidimensional-array


    【解决方案1】:

    您需要使用Array.GetLowerBoundArray.GetUpperBound 方法遍历数组。 Array.IndexOfArray.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 methodArray.Rank property 很有用。我建议设置一个小的多维数组并使用所有这些方法和属性来了解它们的工作原理。

    【讨论】:

      【解决方案2】:

      您尝试过 LINQ 吗?也许类似于(伪代码):

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

      仅供参考,如果您像这样声明数组,这应该可以工作:

      string[][] test
      

      【讨论】:

      • 它是多维的,因此包含不起作用,因为项目本身是一个数组
      • 好的,然后用 Contains 替换数组友好的代码(就像我说的,伪代码)。而不是包含,如何在 where item.IndexOf(OtherVariable) >= 0 ?我会更新我的答案。
      【解决方案3】:

      你需要做类似的事情..

      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
      

      这将逐步循环遍历数组的所有维度。

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        与您之前提出的问题类似

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

        【讨论】:

          猜你喜欢
          • 2013-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-11
          • 1970-01-01
          • 2019-07-24
          • 2019-07-05
          相关资源
          最近更新 更多