user906763
user906763

Reputation: 191

Initializing two dimensional array of objects

I have a 2-dimensional array of objects, which I initialize using the traditional loop:

PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1];
for (int i = 0; i <= LoopCounterMaxValue; i++)
   for (int j = 0; j <= LoopCounterMaxValue; j++)
      tempPb1[i, j] = new PairDS();

Is there any better way to do this using Enumerable or something?

Upvotes: 3

Views: 5406

Answers (3)

John Alexiou
John Alexiou

Reputation: 29244

I thought Initialize could do it, but it only works with value types.

int N = 10;
PairDS[,] temp = new PairDS[N + 1, N + 1];
temp.Initialize();

What I recommend you do is use a jagged array.

class PairDS { public PairDS(int row, int col) { } }


static void Main(string[] args)
{
    int N = 10;
    PairDS[][] temp = Enumerable.Range(0, N + 1).Select(
        (row) => Enumerable.Range(0, N + 1).Select(
            (col) => new PairDS(row, col)).ToArray()).ToArray();
}

Upvotes: 1

JaredPar
JaredPar

Reputation: 754565

There's no way to directly initialize a 2D array with the Enumerable types and as some users have pointed out there's nothing directly wrong with what you're doing. If you're just looking to simplify the loop though this might be what you're looking for;

const int length = LoopCounterMaxValue + 1;
PairDS[,] tempPb1 = new PairDS[length, lenth];
for (var i = 0; i < length * length; i++) {
  var column = i % length;
  var row = (i - column) / length;
  tempPb1[row, column] = new PairDS();
}

Upvotes: 1

Russ Clarke
Russ Clarke

Reputation: 17909

I don't believe you can represent a multi-dimensional array as an Enumerable or List, directly because it (the CLR) has no way of knowing how you intend to index the array.

If you did work it out row by row, it'd actually be worse (ie slower) then simply looping through the array as you're doing and initializing each cell.

Upvotes: 1

Related Questions