tags:

views:

172

answers:

2

How would you store a vector of N dimensions in a datatable in C#?

+2  A: 

For truly n-dimensional stuff, you're probably going to have to drop to simpler concepts - maybe a multi-dimensional array (T[,...,]).

Things like jagged arrays (T[]...[]) or wrappers using List<T> etc are feasible if the number of dimensions is known and constant (but > 1).

An example using an Array of unknown dimension:

    int[] dimensions = { 3, 2, 5 }; // etc
    Array arr = Array.CreateInstance(
        typeof(int), dimensions);
    int[] index = {0,0,0}; // etc
    arr.SetValue(3, index);

But obviously it is easier if the dimensions are known:

    int[, ,] arr = new int[3, 2, 5];
    arr[0, 0, 0] = 3;

The problem with multi-dimension arrays is that they can quickly get too big for the CLR to touch... which is where jagged arrays or other wrappers come in handy (by splitting it into multiple smaller objects) - but making construction much harder:

    int[][][] arr = new int[3][][];
    for(int i = 0 ; i < 3 ; i++) {
        arr[i] = new int[2][];
        for(int j = 0 ; j < 2 ; j++) {
            arr[i][j] = new int[5];
        }            
    }
    arr[0][0][0] = 3;

Any of these can usually be wrapped inside a class, which is probably the sensible approach.

Marc Gravell
Or you can use a jagged array int[][][] if each dimension is going to be different sizes.
Nick Berardi
It'd be easy enough to built a collection based around the array code mentioned.
Brian
@Nick - indeed; jagged example added; it just takes longer to get the code right! It is quite hard to work with jagged arrays if you are unsure of the *number* of dimensions, though.
Marc Gravell
How does any of this relate to datatable?
Dave Van den Eynde
@Dave - DataTable is fixed at 2D. To go above 2D you may need different tricks.
Marc Gravell
@Marc - uhm no, I think Lucero's answer is more valid.
Dave Van den Eynde
Don't forget you'd need a column per *unit* in that dimension, multiplied by all the previous dimension/units - you'd very quickly have an obscene number of columns. As always, YMMV etc...
Marc Gravell
Yes, you'd have an obscene number of columns, but it's the only way to put an n-dimensional array into a datatable. Your answer doesn't even datatable at all! How is that a valid answer?
Dave Van den Eynde
@Dave - you are missing my point; if somebody asks "how do I put screws in with a hammer", then "hit them really hard" is (int your terms) a "valid answer", but it perhaps isn't as useful as suggesting they use a screwdriver. DataTable is *not* a good way to store multi-dimensional data.
Marc Gravell
+1  A: 

If the number of dimensions is known in advance, you could just create one "column" per dimension.

Lucero