发现在一个二维阵列的元件的位置? [英] Finding position of an element in a two-dimensional array?
本文介绍了发现在一个二维阵列的元件的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这里好了简单的问题(也许不是一个简单的答案?)
Well simple question here (maybe not a simple answer?)
说我有一个二维数组
[0] [1] [2]
[3] [4] [5]
[6] [7] [8]
现在假设我想要得到的数字6的位置
Now suppose I want to get the position of the number 6
我知道有一维数组我可以用Array.indexOf(),但我会选择与2维数组是什么?
I know with a one-dimensional array i can use Array.indexOf() but what would my options be with 2-dimensional arrays?
谢谢!
推荐答案
我说是这样的:
public static Tuple<int, int> CoordinatesOf<T>(this T[,] matrix, T value)
{
int w = matrix.GetLength(0); // width
int h = matrix.GetLength(1); // height
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
if (matrix[x, y].Equals(value))
return Tuple.Create(x, y);
}
}
return Tuple.Create(-1, -1);
}
这篇关于发现在一个二维阵列的元件的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文