[英]Initializing jagged arrays
我想在 C# 中創建數組 10 * 10 * 10 像int[][][]
(不是int[,,]
)。
我可以寫代碼:
int[][][] count = new int[10][][];
for (int i = 0; i < 10; i++)
{
count[i] = new int[10][];
for (int j = 0; j < 10; j++)
count[i][j] = new int[10];
}
但我正在尋找一種更美麗的方式。 可能是這樣的:
int[][][] count = new int[10][10][10];
int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3);
使用
static T CreateJaggedArray<T>(params int[] lengths)
{
return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths);
}
static object InitializeJaggedArray(Type type, int index, int[] lengths)
{
Array array = Array.CreateInstance(type, lengths[index]);
Type elementType = type.GetElementType();
if (elementType != null)
{
for (int i = 0; i < lengths[index]; i++)
{
array.SetValue(
InitializeJaggedArray(elementType, index + 1, lengths), i);
}
}
return array;
}
你可以試試這個:
int[][][] data =
{
new[]
{
new[] {1,2,3}
},
new[]
{
new[] {1,2,3}
}
};
或者沒有明確的值:
int[][][] data =
{
new[]
{
Enumerable.Range(1, 100).ToArray()
},
new[]
{
Enumerable.Range(2, 100).ToArray()
}
};
沒有內置的方法來創建數組並在其中創建所有元素,因此它甚至不會像您希望的那樣簡單。 這將與實際工作一樣多。
您可以創建一個方法來創建數組及其中的所有對象:
public static T[] CreateArray<T>(int cnt, Func<T> itemCreator) {
T[] result = new T[cnt];
for (int i = 0; i < result.Length; i++) {
result[i] = itemCreator();
}
return result;
}
然后你可以使用它來創建一個三級鋸齒狀數組:
int[][][] count = CreateArray<int[][]>(10, () => CreateArray<int[]>(10, () => new int[10]));
在Linq 的幫助下
int[][][] count = new int[10][][].Select(t => new int[10][].Select(tt => new int[10]).ToArray()).ToArray();
它肯定不漂亮,可能也不快,但它是單線的。
沒有比編寫 2 個 for 循環更“優雅”的方式了。 這就是為什么它們被稱為“鋸齒狀”,每個子陣列的大小可能會有所不同。
但這留下了一個問題:為什么不使用 [,,] 版本?
int[][][] count = Array.ConvertAll(new bool[10], x =>
Array.ConvertAll(new bool[10], y => new int[10]));
一個 3 維數組聽起來像是創建自己的類的好例子。 面向對象可以是美麗的。
您可以使用具有相同數據表的數據集。 這可能表現得像一個 3D 對象(xyz = 行、列、表)……但是無論你做什么,最終都會得到一些大的東西; 你仍然需要考慮 1000 個項目。
你為什么不試試這個?
int[,,] count = new int[10, 10, 10]; // Multi-dimentional array.
你看到這種表示有什么問題嗎??
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.