【问题标题】:I need to get the row and column value from a 2d array in C#我需要从 C# 中的二维数组中获取行和列值
【发布时间】:2017-04-12 10:19:43
【问题描述】:

我完全被难住了。我在 50x50 二维数组中的随机位置插入了字符串,我需要按字符串过滤数组,找到它的索引,并以某种方式从该索引获取行/列(或 x,y 坐标)。 我正在使用 C#。我觉得没有必要解释更大的程序,因为这是我唯一的挂断。

我应该改用列表吗?我不能在二维数组上使用 indexOf 方法,所以它不起作用。

【问题讨论】:

  • 如果您想要一个简单的二次时间算法,请使用双嵌套 for 循环遍历 2D 数组的每个元素并进行字符串比较,如果找到则返回 (x,y) 值.
  • 在下面查看我的答案。
  • 我很感激!我现在就去看看。

标签: c# .net arrays linq


【解决方案1】:

参考:Accessing Two-Dimensional Array Elements

using System;
    namespace ArrayApplication
    {
       class MyArray
       {
          static void Main(string[] args)
          {
             /* an array with 5 rows and 2 columns*/
             int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
             int i, j;

             /* output each array element's value */
             for (i = 0; i < 5; i++)
             {
                for (j = 0; j < 2; j++)
                {
                   Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
                }
             }
             Console.ReadKey();
          }
       }
    }

输出:

    a[0,0]: 0
    a[0,1]: 0
    a[1,0]: 1
    a[1,1]: 2
    a[2,0]: 2
    a[2,1]: 4
    a[3,0]: 3
    a[3,1]: 6
    a[4,0]: 4
    a[4,1]: 8

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2013-05-14
    • 2011-04-22
    • 1970-01-01
    • 2012-06-20
    • 2012-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多