Initializing jagged arrays

故事扮演 提交于 2019-11-27 20:37:01
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;
}

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()
    }
};

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]));

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

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?

int[][][] count = Array.ConvertAll(new bool[10], x =>
                  Array.ConvertAll(new bool[10], y => new int[10]));

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.

With a little help from Linq

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

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

Why don't you try this?

int[,,] count = new int[10, 10, 10]; // Multi-dimentional array.

Any problem you see with this kind of representation??

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!