我正在嘗試在C#中調整3D數組的大小。調整3D陣列大小
VB6的代碼讀取:
ReDim Combos(ProductNum, 4, 3)
既然不能用於三維陣列使用Array.Resize
,有另一種方式爲我做的在C#中這個功能呢?
我已宣佈將數組作爲3D陣列:
int[ , , ] Combos;
但我無法調整其大小。有任何想法嗎?
我正在嘗試在C#中調整3D數組的大小。調整3D陣列大小
VB6的代碼讀取:
ReDim Combos(ProductNum, 4, 3)
既然不能用於三維陣列使用Array.Resize
,有另一種方式爲我做的在C#中這個功能呢?
我已宣佈將數組作爲3D陣列:
int[ , , ] Combos;
但我無法調整其大小。有任何想法嗎?
沒有辦法直接重新調整.NET中的多維數組。我建議分配一個新的數組,然後使用Array.Copy
將值複製到它。
這就是說,根據你在做什麼,你也可以考慮使用不同的集合類型。在集合方面,.NET中有比VB6更多的選項,所以很多使用多維數組的情況更適合於其他集合類型,尤其是在要調整大小時。
即使對於一維數組,在C#中,數組調整大小的工作方式是將元素複製到新的重新調整大小的數組中。
如果你需要經常重新調整數組的大小,那麼收集會是更好的解決方案。
如果你仍然想調整陣列,這裏是代碼:
T[,,] ResizeArray<T>(T[,,] original, int xSize, int ySize, int zSize)
{
var newArray = new T[xSize, ySize, zSize];
var xMin = Math.Min(xSize, original.GetLength(0));
var yMin = Math.Min(ySize, original.GetLength(1));
var zMin = Math.Min(zSize, original.GetLength(2));
for (var x = 0; x < xMin; x++)
for (var y = 0; y < yMin; y++)
for (var z = 0; z < zMin; z++)
newArray[x, y, z] = original[x, y, z];
return newArray;
}
代碼:
public int[,,] ReDimension(int[,,] OldArray,int arr1stDimLength,int arr2ndDimLength,int arr3rdDimLength)
{
// declare a larger array
int[,,] NewArray = new int[arr1stDimLength,arr2ndDimLength,arr3rdDimLength];
// determine if we are shrinking or enlarging
const int FirstDimension = 0;
const int SecondDimension = 1;
const int ThirdDimension = 2;
int xMax = 0;
int yMax = 0;
int zMax = 0;
// determine if we are shrinking or enlarging columns
if (OldArray.GetUpperBound(FirstDimension) < (arr1stDimLength - 1))
xMax = OldArray.GetUpperBound(FirstDimension) + 1;
else
xMax = arr1stDimLength;
// determine if we are shrinking or enlarging rows
if (OldArray.GetUpperBound(SecondDimension) < (arr2ndDimLength - 1))
yMax = OldArray.GetUpperBound(SecondDimension) + 1;
else
yMax = arr2ndDimLength;
// determine if we are shrinking or enlarging depth
if (OldArray.GetUpperBound(ThirdDimension) < (arr3rdDimLength - 1))
zMax = OldArray.GetUpperBound(ThirdDimension) + 1;
else
zMax = arr3rdDimLength;
// place values of old array into new array
for(int z = 0; z < zMax; z++)
{
for(int x = 0; x < xMax; x++)
{
for(int y = 0; y < yMax; y++)
{
NewArray[x, y, z] = OldArray[x, y, z];
Console.Write("[{0}]", NewArray[x, y, z]);
}
Console.Write("\n");
}
Console.Write("\n\n");
}
return NewArray;
}
來自http://www.codeproject.com/Articles/2503/Redhotglue-C-ArrayObject
經測試,在C#(VS 2008)用控制檯應用程序:
static void Main(string[] args)
{
int[, ,] combos = new int[1,2,3];
Console.WriteLine("Combos size: {0}",combos.Length.ToString());
combos = ReDimension(combos, 5, 5, 5);
Console.WriteLine("New Combos size: {0}", combos.Length.ToString());
Console.ReadKey();
}
似乎工作正常。
我試圖使用Array.Copy,但不確定它是如何工作的。 – 2012-07-05 16:19:32
請參閱http://stackoverflow.com/questions/6539571/how-to-resize-multidimensional-2d-array-in-c – ken2k 2012-07-05 16:24:06
有沒有原因,你爲什麼使用數組而不是列表? –
RobIII
2012-07-05 16:24:33