Count 2D array

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello all,

I have a 2D array called Info[,]. This is of variable size and I'm
struggling to find out how to count the number of elements in the first
dimention.

I've tried all sorts. Can anyone please help?

Thanks,

Jon
 
Hi Jon,

Use the GetUpperBound(index) method as in the code below, this gives you the
highest index, in this case 4 (zero based), hence 5 elements.

int[,] myarray = new int[5, 2];

myarray[0, 0] = 0; myarray[0, 1] = 1;
myarray[1, 0] = 2; myarray[1, 1] = 3;
myarray[2, 0] = 4; myarray[2, 1] = 5;
myarray[3, 0] = 6; myarray[3, 1] = 7;
myarray[4, 0] = 8; myarray[4, 1] = 9;

int ele = myarray.GetUpperBound(0) + 1;

Console.WriteLine("The first index contains {0} elements", ele);
Console.Read();

Hope this helps

Publicjoe

C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html
VB Tutorial at http://www.publicjoe.f9.co.uk/vbnet/vbnet.html
VB Ebook at http://www.publicjoe.f9.co.uk/vbnet/samples/ebook.html
 
Thanks mate, just the job!

Publicjoe said:
Hi Jon,

Use the GetUpperBound(index) method as in the code below, this gives you the
highest index, in this case 4 (zero based), hence 5 elements.

int[,] myarray = new int[5, 2];

myarray[0, 0] = 0; myarray[0, 1] = 1;
myarray[1, 0] = 2; myarray[1, 1] = 3;
myarray[2, 0] = 4; myarray[2, 1] = 5;
myarray[3, 0] = 6; myarray[3, 1] = 7;
myarray[4, 0] = 8; myarray[4, 1] = 9;

int ele = myarray.GetUpperBound(0) + 1;

Console.WriteLine("The first index contains {0} elements", ele);
Console.Read();

Hope this helps

Publicjoe

C# Tutorial at http://www.publicjoe.f9.co.uk/csharp/tut.html
C# Ebook at http://www.publicjoe.f9.co.uk/csharp/samples/ebook.html
VB Tutorial at http://www.publicjoe.f9.co.uk/vbnet/vbnet.html
VB Ebook at http://www.publicjoe.f9.co.uk/vbnet/samples/ebook.html

Jon said:
Hello all,

I have a 2D array called Info[,]. This is of variable size and I'm
struggling to find out how to count the number of elements in the first
dimention.

I've tried all sorts. Can anyone please help?

Thanks,

Jon
 
Back
Top