Nested for loops is generally most readable/accepted approach to initialize 2d array.
If you really need single statement - one option is to use Enumerable.Aggregate (to create/fill array in single statement) and Enumerable.Range + Enumerable.SelectMany (to create indexes using How do I take the Cartesian join of two lists in c#?):
Board = Enumerable.Range(0, BoardHeight)
.SelectMany(x => Enumerable.Range(0, BoardWidth), (row,col)=>new {row,col})
.Aggregate(new Field[BoardHeight, BoardWidth],
(board, position)=>
{
board[position.row,position.col] = new Field();
return board;
});
(Readability of this code is open for discussion)
A bit more practical solution:
for (var i = 0; i < BoardHeight* BoardWidth; i++)
{
Board[i / BoardWidth, i % BoardWidth] = new Field();
}
If you really need "single line initialization" - refactor nested for loop into method (possibly generic) and call it wherever you want with "single line". Something like:
public TField[,] InitializeArray<TField>(
int BoardHeight, int BoardWidth) where TField:new()
{
var Board = new TField[BoardHeight, BoardWidth];
for (int i = 0; i < BoardHeight; i++)
{
for (int j = 0; j < BoardWidth; j++)
{
Board[i, j] = new TField();
}
}
return Board;
}
Lengthwill expose the total length of the array, and you can just use modulo overRankto figure out what indices you needfor (var i = 0; i < BoardHeight* BoardWidth; i++) { Board[i/BoardWidth, i%BoardWidth] = new Field();}) but it is less readable (and unlikely any faster)