您可以使用一个交错数组:
private static readonly int[][] matrix = new int[6][];
matrix[0] = new int[] { 1, 2, 3, 4, 5, 6 };
matrix[1] = new int[] { 7, 8, 9, 10, 11, 12 };
matrix[2] = new int[] { 13, 14, 15, 16, 17, 18 };
matrix[3] = new int[] { 19, 20, 21, 22, 23, 24 };
matrix[4] = new int[] { 25, 26, 27, 28, 29, 30 };
matrix[5] = new int[] { 31, 32, 33, 34, 35, 36 };
使用Linq查找x和y值:
int num = 15;
var matches = matrix
.Select((yArr, index) => new { yArr, yPos = index + 1 })
.Where(y => y.yArr.Contains(num))
.Select(y => new
{
X = (y.yArr.Select((x, i) => new { x, i })
.First(x => x.x == num).i) + 1,
Y = y.yPos,
});
if(matches.Any())
{
var firstMatch = matches.First();
int x = firstMatch.X;
int y = firstMatch.Y;
}
演示
y=0
?我以为x和y都从1开始。然而,我的查询对于6返回X:6 Y:1
。链接 - Tim Schmelter