在多维数组中获取特定的整数(0)维度(C#UNITY)

时间:2018-05-23 07:17:29

标签: c# android arrays unity3d

如何才能在多维数组中只计算我想要的特定整列

我按照这个计算我的整个列和行

//COLUMN
for(int col = 0; col < table.GetLength(0); col++)
{
    int sum = 0;
    //ROW
    for (int row = 0; row < table.GetLength(1); row++)
    {
         if (table[col,row] != null)
         {
             sum++;
         }
    }
     Debug.Log("table column: " + col + " has " + sum + " data");
}

我想要的只是获取特定的整个列然后移动到另一个列就像那样。我需要这样做,因为我需要将它与最后一列的值进行比较。

例如:我想检查第二列中有多少数据,然后将其与第一列进行比较。

2 个答案:

答案 0 :(得分:2)

你几乎就在那里。您所要做的就是将当前列的总和存储到列表中:

var List<int> sums = new List<int>();
//COLUMN
for(int col = 0; col < table.GetLength(0); col++)
{
    int sum = 0;
    //ROW
    for (int row = 0; row < table.GetLength(1); row++)
    {
         if (table[col,row] != null)
         {
             sum++;
         }
    }
    Debug.Log("table column: " + col + " has " + sum + " data");
    sums.Add(sum);
}

现在,您可以轻松地比较第1列和第2列的行数:

bool areEqual = sums[0] == sums[1];

答案 1 :(得分:0)

有一个解决方案:)

//generic function
public static int CountRow<T>(T[,] table, int col)
{
    if (table == null || col < 0 || col >= table.GetLength(1)) 
    {
        //handle error
        return -1;
    }

    //this is the same as the block of the outer for loop
    int sum = 0;
    for (int row = 0; row < table.GetLength(1); row++)
    {
        if(table[col,row] != null)
        {
            sum++;
        }
    }
    return sum;
}

然后像这样使用它

int prevSum = -1;
for (int col = 0; col < table.GetLength(0); ++col)
{
    int sum = CountRow(table, col);
    Debug.Log("table column :" + col + " has " + sum + " data");
    if (sum == prevSum)
    {
       //comparison happens
    }
}