// Two-dimensional array.  
int[,] array2D = new int[,]
{
{ 1, 2 },
{ 3, 4 },
{ 5, 6 },
{ 7, 8 }
};
// A similar array with string elements. 
string[,] array2Db = new string[3, 2]
{
{ "one", "two" },
{ "three", "four" },
{ "five", "six" }
};
// Three-dimensional array. 
int[, ,] array3D = new int[,,]
{
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
 // The same array with dimensions specified. 
int[, ,] array3Da = new int[2, 2, 3]
{
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};

Initializing Two-Dimensional Arrays

int [,] a = new int [3,4] {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

Accessing Two-Dimensional Array Elements

class MyArray {       
static void Main(string[] args) {
/* an array with 5 rows and 2 columns*/
int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
int i, j;

/* output each array element's value */
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}

Console.ReadKey();
}
}

Difference Between Length, Count, Rank

  • LengthTotal number of elements in an array
  • LongLength: Same as Length, but returned as long (in case it’s >= 231)
  • Count(): LINQ extension method that works with other collection types as well
  • Rank: Number of dimensions in array (always 1 for vectors). Only in .NET 3.5+.
  • GetLength()GetLongLength()Length of a certain dimension of an array
  • GetLowerBound(): Starting index of a certain dimension of an array; always 0 for vectors
  • GetUpperBound(): Ending index of a certain dimension of an array; always Length - 1 for vector

string[,] a = {
{“0”, “1”, “2”},
{“0”, “1”, “2”},
{“0”, “1”, “2”},
{“0”, “1”, “2”},
};

// a.Length = 12

Use Array.Rank to get number of dimensions and then use Array.GetLength(int dimension) to get the length of a specific dimension.

Last modified: April 1, 2019

Author

Comments

Write a Reply or Comment