29

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];
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155

8 Answers8

26
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;
}
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    is there any way to do this while also setting the array values to something other than zero? like say, -1? – metinoheat Jan 15 '15 at 14:37
  • Great answer, really well thought. – mafu May 02 '15 at 12:17
  • @metinoheat, I think it can be done like this: `if (elementType != null) { ... } else { for (int i = 0; i < lengths[index]; i++) { array.SetValue(-1, i); } }` – Pavel May 20 '18 at 01:16
22

You could try this:


int[][][] data =
{
    new[]
    {
        new[] {1,2,3}
    }, 
    new[]
    {
        new[] {1,2,3}
    }
};

Or with no explicit values:


int[][][] data =
{
    new[]
    {
        Enumerable.Range(1, 100).ToArray()
    }, 
    new[]
    {
        Enumerable.Range(2, 100).ToArray()
    }
};

Mecaveli
  • 1,507
  • 10
  • 16
  • 1
    I wonder why is this not voted up... for types other than `int`: `double[] data = {new double[] {1, 4, 2}, new double[] {7, 4, 2,1, 0.66, 5.44}, new double[] {1.2345678521, 874347665423.12347234563233, 5e33, 66e234, 6785e34}};` – Happypig375 Dec 21 '16 at 14:17
  • This is a great answer since it purely relies on built in language. If one wants to simple access primitive data types and not write too much boilerplate this is sweet. – MSB Apr 11 '21 at 09:58
8

There is no built in way to create an array and create all elements in it, so it's not going to be even close to how simple you would want it to be. It's going to be as much work as it really is.

You can make a method for creating an array and all objects in it:

public static T[] CreateArray<T>(int cnt, Func<T> itemCreator) {
  T[] result = new T[cnt];
  for (int i = 0; i < result.Length; i++) {
    result[i] = itemCreator();
  }
  return result;
}

Then you can use that to create a three level jagged array:

int[][][] count = CreateArray<int[][]>(10, () => CreateArray<int[]>(10, () => new int[10]));
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

With a little help from Linq

int[][][] count = new int[10].Select(x => new int[10].Select(x => new int[10]).ToArray()).ToArray();

It sure isn't pretty and probably not fast but it's a one-liner.

SDM
  • 43
  • 4
Bizniztime
  • 1,016
  • 10
  • 22
2
int[][][] count = Array.ConvertAll(new bool[10], x =>
                  Array.ConvertAll(new bool[10], y => new int[10]));
Slai
  • 22,144
  • 5
  • 45
  • 53
0

A three dimensional array sounds like a good case for creating your own Class. Being object oriented can be beautiful.

JamesBrownIsDead
  • 125
  • 1
  • 1
  • 5
0

You could use a dataset with identical datatables. That could behave like a 3D object (xyz = row, column, table)... But you're going to end up with something big no matter what you do; you still have to account for 1000 items.

tsilb
  • 7,977
  • 13
  • 71
  • 98
0

There is no 'more elegant' way than writing the 2 for-loops. That is why they are called 'jagged', the sizes of each sub-array can vary.

But that leaves the question: why not use the [,,] version?

H H
  • 263,252
  • 30
  • 330
  • 514
  • 8
    Multidimensional arrays are allocated as one big block of memory, jagged arrays are separate blocks - if there's lots of memory usage, the multidimensional array is more likely to cause OutOfMemoryException. Accessing a jagged array is also faster (as the CLR is optimized for SZ arrays - single dimension, zero-based) – thecoop Nov 15 '09 at 22:24
  • thecoop, you are right on both counts but neither amounts to much as long as size=10, or even 100. But beyond that, it quickly adds up. – H H Nov 15 '09 at 22:27
  • @thecoop, Have you actually **tested** what you claim? I'm curious. – strager Nov 16 '09 at 02:39