How to extract a single array from a multidimensional array in C#? Is there any shortcut to do this?
for (int i = 0; i < 50; i++)
{
HUYArrayEnd[i] = HUYArray[500, 0, i];
}
How to extract a single array from a multidimensional array in C#? Is there any shortcut to do this?
for (int i = 0; i < 50; i++)
{
HUYArrayEnd[i] = HUYArray[500, 0, i];
}
You can use Linq:
HUYArrayEnd = Enumerable.Range(0, 50).Select(x => HUYArray[500, 0, x]).ToArray();
Working Example:
int[,,] HUYArray = new int[501,501,501];
int[] HUYArrayEnd;
for(int i=0;i<501;i++){
for(int j=0;j<501;j++){
for(int k=0;k<501;k++){
HUYArray[i,j,k]=i+j+k;
}
}
}
HUYArrayEnd = Enumerable.Range(0, 50).Select(x => HUYArray[500, 0, x]).ToArray();
If you want all elements from, for example, the index [500, 0, *], you can use
HUYArrayEnd = Enumerable.Range(0, HUYArray.GetLength(2))
.Select(x => HUYArray[500, 0, x])
.ToArray();
Not an answer to your exact question, but may solve your problem.
If you have a method that accepts a single-dimensional array:
void Foo(int[] input)
{
for (var i = 0; i< 50; i++)
Bar(input[i]);
}
And you are calling it like this:
for (int i = 0; i < 50; i++)
{
HUYArrayEnd[i] = HUYArray[500, 0, i];
}
Foo(HUYArrayEnd);
Then you can replace the array parameter with a partial function:
void Foo(Func<int,int> input)
{
for (var i = 0; i< 50; i++)
Bar(input(i));
}
And then pass it like this:
Foo(i => HUYArray[500,0,i]);
This solution eliminates the need to allocate and copy the array.