3

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?

1
  • Nothing, but it does look verbose. Commented Aug 22, 2011 at 23:04

3 Answers 3

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes Jagged array is another good idea to think about. Thanks for your cooperation.
1

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.

Comments

1

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();
}

2 Comments

Those operations %, /, * don't simplify and need more time to understand what is going on...
@archer I think it's about perspective. I for one find it easier to read cause I've used and seen it used numerous times. I'm sure it's not simpler at a glance. The OP's question was unclear to their intent and I wanted to provide a simplification by removing the nesting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.