您可以使用锯齿状数组:
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;
}
演示