Ginxxx
Ginxxx

Reputation: 1648

Get the Specific Column and Row of 2 dimentional Array C#

how could i possible get the specific column and row of my 2 dimensional array . It is declared like this

string[,] table = new string[104, 6];

I want to get the column [2,0](3rd column) and compare it to the [2,1](3rd column,1st row) but if there's no value in [2,1] then I'll compare it to the [3,0](4th column).

I tried doing it like this

string[,] table2 = new string[104, 6];
string newPreviousValue2 = "placeholder";
int xIndex2 = 0;
int yIndex2 = 0;

string thirdColumn = table2[3, 0];
string firstRowinThirdColumn = table2[4, 0];

foreach (string previousValue in newChars)
{
    if (table2.GetLength(0) < xIndex2)
            {
                break;
            }
            if (previousValue.Equals(newPreviousValue2) && yIndex2 < table2.GetLength(1) - 1) {

                table2[xIndex2, yIndex2] = previousValue;

                var col = 2;
                var row = 0;

                var origin = table2[col, row];
                var other = table2[col, row + 1] ?? table2[col + 1, row];
                if (origin != null && origin == other)
                {
                    Debug.Log("There's something in 3rd Column 2nd row ");
                }
                else
                {
                    Debug.Log("There's nothing in 3rd column 2nd Row so Move to 4th Column");
                }
            }
            newPreviousValue2 = previousValue;
}

But i couldn't get it . What I'm trying to achieve is I'm going to start from the 3rd column but if there is no 2nd row on the 3rd column it will go compare the 3rd column first row to 4th column first row and so on.

EDIT:

Now i have this data : PP ,B ,P ,P ,B

This will be like this

enter image description here

the code @Immersive provided is this

var col = 2;
var row = 0;

var origin = table2[col, row];
var other = table2[col, row + 1] ?? table2[col + 1, row];
if (origin != null && origin == other)
{
     Debug.Log("There's something in 3rd Column 2nd row ");
}
else
{
      Debug.Log("There's nothing in 3rd column 2nd Row so Move to 4th Column");
}

It always fall to the else statement

Upvotes: 0

Views: 95

Answers (1)

Immersive
Immersive

Reputation: 1704

Barring boundary checks:

var column = 2;
var row = 0;

var origin = table2[column, row];
var other = table2[column, row + 1] ?? table2[column + 1, row];

if ( origin != null && origin == other )
{ }

The ?? is called the "coalesce" operator. It's a shorthand for (A != null) ? A : B

Upvotes: 2

Related Questions