2

for a single dimensional array normally I would use a for loop like the one below but I can't think of a way to do this that doesn't involve lots of loops.

for (int i = 0; i < myArray.length; ++i)
{
    myArray[i] = rnd.Next(1, 500);
}
Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
anthony corrado
  • 91
  • 1
  • 1
  • 5

2 Answers2

5

You can try low level Buffer.BlockCopy to conceal the loop(s):

  // N-D array (whatever dimensions)
  int[,,] array = new int[3, 5, 11]; 

  Buffer.BlockCopy(
    Enumerable
      .Range(0, array.Length)
      .Select(x => rand.Next(0, 500))
      .ToArray(),
    0,
    array,
    0,
    array.Length * sizeof(int)); // sizeof(int) : we copy bytes...

we create 1-D array

    Enumerable
      .Range(0, array.Length)
      .Select(x => rand.Next(0, 500))
      .ToArray()

with the total length of N-D one (array.Length == array.Length(0) * ... * array.GetLEngth(N)) and copy it into N-D one.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    This won't work because it copies the result of the `Enumerable` and doesn't manipulate the source array. You basically manipulate a temporary array and do nothing with it. – Tamir Vered Dec 07 '16 at 13:08
  • 1
    @Tamir Vered: Thank you! You're quite right: I put the routine prematurely: wrong argument order (source and target swapped) and wrong *bytes* size (should have been multiplied by `sizeof(int)`) – Dmitry Bychenko Dec 07 '16 at 13:19
0

Use more than one loop:

for (int i = 0; i < myArray.Length; ++i)
{
    for (int j = 0; j < myArray[i].Length; ++j)
    {
        myArray[i][j] = rand.Next(0, 500);
    }
}
PC Luddite
  • 5,883
  • 6
  • 23
  • 39