Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing jagged arrays

Tags:

I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,]).

I can write code:

int[][][] count = new int[10][][];  for (int i = 0; i < 10; i++)  {     count[i] = new int[10][];      for (int j = 0; j < 10; j++)         count[i][j] = new int[10]; } 

but I am looking for a more beautiful way for it. May be something like that:

int[][][] count = new int[10][10][10]; 
like image 767
AndreyAkinshin Avatar asked Nov 15 '09 21:11

AndreyAkinshin


People also ask

How do you initialize a jagged array?

A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays. jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2]; Each of the elements is a single-dimensional array of integers.

What are the elements of jagged array are initialized to if they are not initialized by the user?

The elements of Jagged Array are reference types and initialized to null by default.

What is the use of jagged array in C#?

Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays. An array may be defined as a sequential collection of elements of the same data type.


1 Answers

int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3); 

using

static T CreateJaggedArray<T>(params int[] lengths) {     return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths); }  static object InitializeJaggedArray(Type type, int index, int[] lengths) {     Array array = Array.CreateInstance(type, lengths[index]);     Type elementType = type.GetElementType();      if (elementType != null)     {         for (int i = 0; i < lengths[index]; i++)         {             array.SetValue(                 InitializeJaggedArray(elementType, index + 1, lengths), i);         }     }      return array; } 
like image 166
dtb Avatar answered Sep 17 '22 10:09

dtb