1

I've looked and found no definitive answer. I'm looking for the easiest way to set all array elements in a char array to '*'.

public static int GridWidth = 7;
public static int GridHeight = 5;

char[,] Cave = new char[GridWidth, GridHeight]

So i have a multi dimensional array and want to set all of the elements to '*'. Is this a case of iterating through the array to set each of the values, or is there alternative methods?

Graham Warrender
  • 365
  • 1
  • 8
  • 20

2 Answers2

1

Running double for each loop is the easiest way to initialise 2 dimensional array at the moment.

for(int i = 0; i< GridWidth; i++)
   for(int j = 0; j< GridHeight; j++)
      Cave[i,j] = '*'
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
0

I would have gone with the two loops myself and the following would definitely not be easier than for loops:

One liner LINQ:

 Enumerable.Range(0, GridWidth)
.AsParallel()
.ForAll(s => Enumerable.Range(0, GridHeight)
.AsParallel()
.ForAll(p => Cave[s, p] = '*'));
Sourav 'Abhi' Mitra
  • 2,390
  • 16
  • 15