2015-04-30 149 views
0

的访问一名维我有一个多维数组,看起来像这样:多维数组

public static int[,] GameObjects = new int[,] 
{ 
    //Type,X,Y,Width,Height 
    {0,50,50,10,100}, 
    {1,50,150,10,20} 
}; 

我试图访问一个“行”的价值观,并将其储存到一个变量for循环中:

for (int i = 0; i < gameObjectData.Length; i++) 
{ 
    int[] g = gameObjectData[i]; 
} 

我想要g来存储第一个数组的值,所以在第一个循环g中应该存储0,50,50,10,100。该代码给出了错误Wrong number of indices inside []; expected 2

+0

int [,]'和'int [ ] []'是不一样的。我忘了具体细节(现在查找,我找到了,我会发布答案) – Flater

+0

'int [,]'与'int [] []'不一样。您需要将一行的值复制到新数组中。 –

+0

看看这个http://stackoverflow.com/questions/5132397/fast-way-to-convert-a-two-dimensional-array-to-a-list-one-dimensional –

回答

2

没有揭示二维数组从其中获得单维数组的机制。

如果你有一个锯齿状数组,那么它可能:

int[][] array; 
//populate array 
int[] row = array[1]; 

如果你需要有一个多维数组,那么你可以做的最好的是创建一个类来保存到一个二维阵列和行号并公开索引器以访问该行中的项目;它可能看起来与数组类似,但它实际上并不是一个。

像这样的东西会给你裸露的骨头;如果你想让类型扩展为IList<T>,你也可以这样做。

public class ArrayRow<T> : IEnumerable<T> 
{ 
    private T[,] array; 
    private int index; 
    public ArrayRow(T[,] array, int index) 
    { 
     this.array = array; 
     this.index = index; 
    } 

    public T this[int i] 
    { 
     get { return array[index, i]; } 
     set { array[index, i] = value; } 
    } 

    public int Count { get { return array.GetLength(1); } } 

    public IEnumerator<T> GetEnumerator() 
    { 
     for (int i = 0; i < Count; i++) 
      yield return this[i]; 
    } 

    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); 
    } 
} 
public static ArrayRow<T> GetRow<T>(this T[,] array, int index) 
{ 
    return new ArrayRow<T>(array, index); 
} 

或者你可以在多维数组中拷贝每行的值到一个新的单维数组,但随后也不会反映到对方所做的更改。

0

对于multidimensional arrays你需要访问他们像这样:

// access 0,1 
gameObjectData[0,1]; 

// access 5,4 
gameObjectData[5,4]; 

// So in general is 
gameObjectData[x,y]; 

您不能只是给[X],进入这么你的问题将是

// asuming you want row 0 
int row = 0; 

// this give to g the size of the row of gameObjectData 
int[] g = new int[gameObjectData.getLenght(row)]; 

for (int i = 0; i < gameObjectData.getLenght(row); i++) 
{ 
    g[i] = gameObjectData[row,i]; 
} 
0

如果你喜欢单行,这是一个LINQ之一:

int rowIndex = 0; 
firstRow = Enumerable.Range(0, gameObjectData.GetLength(1-rowIndex)) 
        .Select(v => gameObjectData[rowIndex,v]) 
        .ToArray();