0

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];
}
Magnetron
  • 7,495
  • 1
  • 25
  • 41
  • you need a loop per dimension. so 3 loops – Ashkan Mobayen Khiabani Oct 28 '19 at 16:59
  • @KieranDevlin that appears to be a completely diferent question. OP wants to extract a sub-array, not flatten the array. – Magnetron Oct 28 '19 at 17:01
  • The question needs more depth, its hard to gauge the requirements. What does extract one array from a multidimensional array mean? Is there a specific array you want to obtain from the array? etc. – Kieran Devlin Oct 28 '19 at 17:05
  • @KieranDevlin OP should clarify, but by the example the desired result is an array with all the elements of the index `[500, 0, i]` where `i` ranges from 0 to 49. Now whether it's a specific index or the whole `[500, 0, *]`, it's up to clarification. – Magnetron Oct 28 '19 at 17:17

2 Answers2

0

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();
Magnetron
  • 7,495
  • 1
  • 25
  • 41
0

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.

John Wu
  • 50,556
  • 8
  • 44
  • 80