471,618 Members | 1,153 Online

Count 2D array

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.

Thanks,

Jon
Feb 21 '06 #1
2 2272
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);

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" <Jo*@discussions.microsoft.com> wrote in message
news:AE**********************************@microsof t.com...
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.

Thanks,

Jon

Feb 21 '06 #2
Thanks mate, just the job!

"Publicjoe" wrote:
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);

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" <Jo*@discussions.microsoft.com> wrote in message
news:AE**********************************@microsof t.com...
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.

Thanks,

Jon

Feb 21 '06 #3