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];
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.
The elements of Jagged Array are reference types and initialized to null by default.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With