C# 如何保存多维数组索引?

C# 如何保存多维数组索引?,c#,arrays,loops,reference,C#,Arrays,Loops,Reference,基本上,我的第一个任务是将“0”的位置保存为整数。真正简单的标准数组。此代码在数组(大小:8)中循环,直到找到0,然后将其另存为位置。见下面的代码: p、 s:n是对保存在其他地方的数组的引用 int position = 0; this.nodesExpanded++; // Loop through the array to get the position of where '0' is for (int i = 0; i < n.ge

基本上,我的第一个任务是将“0”的位置保存为整数。真正简单的标准数组。此代码在数组(大小:8)中循环,直到找到0,然后将其另存为位置。见下面的代码:

p、 s:n是对保存在其他地方的数组的引用

int position = 0;
        this.nodesExpanded++;
        // Loop through the array to get the position of where '0' is
        for (int i = 0; i < n.getPuzzle().length; i++){
            if (n.getPuzzle()[i] == 0){
                position = i;
                break;
            }
        }
int位置=0;
这个.nodesExpanded++;
//循环遍历数组以获取“0”所在的位置
for(int i=0;i
我的最终任务是为多维数组(大小:[3,3])实现这一点。以下是我迄今为止创造的:

for (int x = 0; x < 3; x++)
        {
            for (int y = 0; y < 3; y++)
            {
                if (n.getPuzzle()[x,y] == 0)
                {
                    **position = ;**
                    break;
                }
            }//end y loop
        }//end x loop
for(int x=0;x<3;x++)
{
对于(int y=0;y<3;y++)
{
如果(n.getPuzzle()[x,y]==0)
{
**位置=**
打破
}
}//末端y形环
}//末端x环
那么,如何将对位置的数组引用保存为值呢? “位置”应该不是int,我猜


如果您需要更多的澄清,请务必发表评论,提前道歉&谢谢

您可以使用
元组来存储该位置。也可以创建自己的数据结构

示例:最后,您可以看到如何访问元组项

var positions = new List<Tuple<int, int>>();

            for (int x = 0; x < 3; x++)
            {
                for (int y = 0; y < 3; y++)
                {
                    if (n.getPuzzle()[x,y] == 0)
                    {
                        positions.Add(new Tuple<int, int>(x,y));
                        break;
                    }
                }//end y loop
            }//end x loop

            if(positions.Any())
            {
                var xpos = positions[0].Item1;
                var ypos = positions[0].Item2;
            }
var positions=新列表();
对于(int x=0;x<3;x++)
{
对于(int y=0;y<3;y++)
{
如果(n.getPuzzle()[x,y]==0)
{
添加(新元组(x,y));
打破
}
}//末端y形环
}//末端x环
if(positions.Any())
{
var xpos=位置[0]。项1;
var ypos=位置[0]。项目2;
}

我发现存储多维数组索引的一种自然方法是使用大小为维度数的一维数组


因此,如果你有一个
对象[,]a
和索引
int[]i
,你可以用表达式
a[i[0],i[1],i[2]]
,它的工作方式与你的一维数组相同,但是你需要保留两个位置值。我使用了
int
s作为示例,但您可能希望使用自定义结构或元组(如AD.Net所述)

intxpos=-1;
int ypos=-1;
对于(int x=0;x<3;x++)
{
对于(int y=0;y<3;y++)
{
如果(n.getPuzzle()[x,y]==0)
{
xpos=x;
ypos=y;
打破
}
}//末端y形环
}//末端x环
如果(!(xpos>-1和&ypos>-1));//找不到0

举个例子,这将是一个更好的答案。该死,我应该考虑这么做。谢谢你的意见!
int xpos = -1;
int ypos = -1;
for (int x = 0; x < 3; x++)
{
    for (int y = 0; y < 3; y++)
    {
        if (n.getPuzzle()[x,y] == 0)
        {
            xpos = x;
            ypos = y;
            break;
        }
    }//end y loop
}//end x loop
if (!(xpos > -1 && ypos > -1)) ; // 0 was not found