Rida Akhtar Rida Akhtar - 3 months ago 9
C# Question

how to get the length of a 2D array in c#? lenght and GetLength are not helping

here is my code. i want to remove some elements from my 2D array. for that i have run a for loop. but don't know how to bound the loop because it keeps giving me error that "index was outside the bounds of array" (if i use Length / GetLength ). :

int len1 = tagged_data.GetLength(0);
int len2 = tagged_data.GetLength(1);
int len = len1 + len2;
Console.WriteLine(len);
for (int i = 0; i <= len1;i++ )
{

if (tagged_data[i, 1] != "'NN'")//|| tagged_data[i, 1] != "'NNS'"|| tagged_data[i, 1] != "'VBD'" || tagged_data[i, 1] != "'VBG'" || tagged_data[i, 1] != "'VB'" || tagged_data[i, 1] != "'VBZ'")
{
tagged_data[i, 1] = null;

}
else if (tagged_data[i, 1] != "'NNS'")
{
tagged_data[i, 1] = "";

}
else if (tagged_data[i, 1] != "'VBD'")
{
tagged_data[i, 1] = "";

}
else if (tagged_data[i, 1] != "'VBG'")
{
tagged_data[i, 1] = "";

}
else if (tagged_data[i, 1] != "'VBZ'")
{
tagged_data[i, 1] = "";

}
else if (tagged_data[i, 1] != "'VB'")
{
tagged_data[i, 1] = "";

}
else
Console.Write("nothing to eliminate");
}

Answer

For loop should be

for (int i = 0; i < len1;i++ )

because length give total size and index start with zero. So last index will be total length - 1.

e.g.

int[] a = {1,2,3,4} will have length 4 but index will be 3.