views:

1917

answers:

2

What is an efficient way to shrink a two dimensional array to a smaller size in C#?

For example:

var bigArray = new object[100, 100];
var smallArray = new object[10, 10];

bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;


startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;

smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);

How will you write SomeShrinkingMethod() ?

Thanks!

EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.

+1  A: 

You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.

The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.

Edit:

In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.

Konrad Rudolph
thanks for your response.. please see the edited sample. I'm simply just trying to copy the first 10x10 objects from bigArray to smallArray. I'm just not sure if there's a more efficient way than running a nested for-loop. Thanks!
stung
for loops are going to do what you want without a lot of unnecessary overhead. If all you're doing is copying, it's the way to go.
Bob King
A: 

Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?

itsmatt