2009-11-15 200 views
12

我想在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]; 

回答

20
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; 
} 
+1

有沒有辦法做到這一點,同時也設置數組值爲零以外的東西?像說,-1? – metinoheat 2015-01-15 14:37:19

+0

很好的回答,真的很好想。 – mafu 2015-05-02 12:17:00

2

三維數組聽起來像創建自己的類的好例子。面向對象可以是美麗的。

0

您可以使用具有相同數據表的數據集。這可能表現得像一個3D對象(xyz = row,column,table)......但是無論你做什麼,你都會得到一些大的東西;你仍然需要考慮1000個項目。

6

沒有內置的方法來創建數組並創建其中的所有元素,所以它不會接近您想要的簡單程度。這將是一樣多的工作,因爲它真的是。

您可以用於創建陣列和方法中的所有對象:

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])); 
+0

尼斯使用遞歸通用的高清initions ... – thecoop 2009-11-15 22:25:23

1

沒有'比編寫2 for循環更優雅的方式。這就是爲什麼他們被稱爲「鋸齒狀」,每個子陣列的大小可能會有所不同。

但是這留下了問題:爲什麼不使用[,,]版本?

+3

將多維數組分配爲一塊大內存塊,鋸齒形數組爲單獨塊 - 如果存在大量內存使用情況,則多維數組更有可能導致OutOfMemoryException。訪問鋸齒狀陣列也更快(因爲CLR針對SZ陣列進行了優化 - 單維度,零度) – thecoop 2009-11-15 22:24:11

+0

thecoop,兩種方法都是正確的,但只要size = 10甚至100,它們的數量都不會太大。除此之外,它很快加起來。 – 2009-11-15 22:27:36

+0

@thecoop,你真的**測試**你聲稱什麼?我很好奇。 – strager 2009-11-16 02:39:43

7

你可以試試這個:

 

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

我想知道爲什麼這不是投票了...除了'int':double [] data = {new double [] {1,4,2},new double [] {7,4,2, 1,0.66,5.44},new double [] {1.2345678521,874347665423.12347234563233,5e33,66e234,6785e34}};'' – Happypig375 2016-12-21 14:17:52

-1
int[][][] count = Array.ConvertAll(new bool[10], x => 
        Array.ConvertAll(new bool[10], y => new int[10]));