Reputation: 409
In Processing (java based language) I can do this;
int [][] a = new int[3][2];
for (int i = 0; i < 3; i++)
{
a[i][0] = i;
a[i][1] = i+3;
}
int [] b = a[2];
b is a one dimensional array with the values 2 and 5. It takes the array in row 2 of array a.
matlab syntax would be
b = a(3,:);
Is there any equivalent for c#? I can't seem to find anything but seems like a fairly useful and obvious feature.
Thanks
Upvotes: 2
Views: 2095
Reputation: 437366
C# has multidimensional arrays, but it also has arrays of arrays (also called jagged arrays). The second form is what you are after:
// This is a jagged array. It has 3 rows, each of which is an int[] in its own right.
// Each row can also have a different number of elements from all the others, so if
// a[i][N] is valid for some i and N, a[x][N] is not necessarily valid for other x != i
var a = new int[3][];
// To populate the array you need to explicitly create an instance for each sub-array
for (int i = 0; i < 3; i++)
{
a[i] = new[] { i, i + 3 };
}
// And now this is possible:
var b = a[2];
If you have a multidimensional array at hand, you will need to do the copying manually.
Upvotes: 3
Reputation: 23324
In addition to the other answers: if you really want a copy, i.e. you don't want b[0] = 42;
to change a[2][0];
, then do this:
int [] b = (int[])a[2].Clone();
Upvotes: 1
Reputation: 20732
C# distinguishes between jagged arrays ([][]
) and multidimensional arrays ([,]
):
Jagged Arrays:
This should be possible; every array element is just an array itself.
Multidimensional Arrays:
Here, you will have to do the copying yourself, element by element.
Upvotes: 1