- Home /
Get the specific whole (0) dimension of a multidimensional array.
How can I possibly count only the specific whole row i want in a multidimensional array
I do the counting of my whole row like this
string[,] table = new string[104, 6];
IEnumerator Win_Log(){
GameObject p = Instantiate(prefab_gameobject) as GameObject;
p.transform.SetParent(pos_big_road);
p.transform.localScale = Vector3.one;
img = (RawImage)p.GetComponent<RawImage>();
//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");
}
}
The problem with this code is that it gets the whole multidimensional array . What i want is just to get the specific whole row then move to another row just like that.
Answer by Harinezumi · May 23, 2018 at 07:53 AM
You almost have it, you just need to remove iteration through all columns. Move the block in the outer for loop into a separate method, and then you can call it separately from anywhere. Like this:
private IEnumerator YourFunction () {
for (int col = 0; col < table.GetLength(0); ++col) {
int sum = CountRow(table, col);
Debug.Log("table column: " + col + " has " + sum + " data");
yield return null;
}
}
// generic function, it will work on any 2D array (mostly because I don't know the type of your table variable :D )
public static int CountRow<T>(T[,] table, int col) {
if (table == null || col < 0 || col >= table.GetLength(0)) {
// handle error
return -1;
}
// this is the same as the block of the outer for loop that you posted
int sum = 0;
for (int row = 0; row < table.GetLength(1); row++) {
if (table[col, row] != null) { sum++; }
}
return sum;
}
Btw, here is a tutorial about 2D arrays in C#: https://www.dotnetperls.com/2d
You misunderstood what I was saying: this isn't a complete solution, this is what should replace the inside of your outer for loop. The error you get is not related to the code I wrote, it is due to how you use it, nor does it matter if you are in an IEnumerator.
If you post your whole function, it will be easier to help, but I'll update my answer with what I think your function is.
Just one more question sir . How can i compare the 1st column to 2nd column ,3rd column to 2nd column , 4th column and 3rd column and so on . Compare if they have the same in length of data
Your answer