tags:

views:

116

answers:

4

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];
+1  A: 

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

JamesBrownIsDead
A: 

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
+3  A: 

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
Nice use of recursive generic definitions...
thecoop
+2  A: 
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