Книга: C# 2008 Programmer

Multidimensional Arrays

Multidimensional Arrays

So far the arrays you have seen are all one-dimensional ones. Arrays may also be multidimensional. To declare a multidimensional array, you can the comma (,) separator. The following declares xy to be a 2-dimensional array:

int[,] xy;

To initialize the two-dimensional array, you use the new keyword together with the size of the array:

xy = new int[3,2];

With this statement, xy can now contain six elements (three rows and two columns). To initialize xy with some values, you can use the following statement:

xy = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

The following statement declares a three-dimensional array:

int[, ,] xyz;

To initialize it, you again use the new keyword together with the size of the array:

xyz = new int[2, 2, 2];

To initialize the array with some values, you can use the following:

int[, ,] xyz;
xyz = new int[,,] {
 { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } }
};

To access all the elements in the three-dimensional array, you can use the following code snippet:

for (int x = xyz.GetLowerBound(0); x <= xyz.GetUpperBound(0); x++)
 for (int y = xyz.GetLowerBound(1); y <= xyz.GetUpperBound(1); y++)
  for (int z = xyz.GetLowerBound(2); z <= xyz.GetUpperBound(2); z++)
   Console.WriteLine(xyz[x, y, z]);

The Array abstract base class contains the GetLowerBound() and GetUpperBound() methods to let you know the size of an array. Both methods take in a single parameter, which indicates the dimension of the array about which you are inquiring. For example, GetUpperBound(0) returns the size of the first dimension, GetUpperBound(1) returns the size of the second dimension, and so on.

You can also use the foreach statement to access all the elements in a multidimensional array:

foreach (int n in xyz)
 Console.WriteLine(n);

These statements print out the following:

1
2
3
4
5
6
7
8

Оглавление книги


Генерация: 0.057. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз