2010-04-28 174 views
7

我已經看過旋轉二維數組上的其他帖子,但它不是我想要的。 我想是這樣的C#,旋轉二維數組

int[,] original= new int[4,2] 
     { 
      {1,2}, 
      {5,6}, 
      {9,10}, 
      {13,14} 
     }; 

我想打開它,這樣, rotatedArray = {{1,5,9,13},{2,6,10,14}}; 我想按列進行一些分析,而不是按行進行分析。

這有效,但有沒有更簡單的方法?

private static int[,] RotateArray(int[,] myArray) 
    { 
     int org_rows = myArray.GetLength(0); 
     int org_cols = myArray.GetLength(1); 

     int[,] myRotate = new int[org_cols, org_rows]; 

     for (int i = 0; i < org_rows; i++) 
     { 
      for(int j = 0; j < org_cols; j++) 
      { 
       myRotate[j, i] = myArray[i, j]; 
      } 
     } 

     return myRotate; 
    } 

有沒有一種簡單的方法來遍歷c#中的列?
B

+0

這將是更簡單,如果你會使用數組的另一種方式: INT [ ] []而不是int [,] – Tigraine 2010-04-28 12:10:25

回答

5

如果將陣列更改爲數組數組,它​​會變得更容易。我發現這一點,如果您將其更改爲int [] []:

int[][] original = new[] 
            { 
             new int[] {1, 2}, 
             new int[] {5, 6}, 
             new int[] {9, 10}, 
             new int[] {13, 14} 
            }; 

和旋轉方法:

private static int[][] Rotate(int[][] input) 
{ 
    int length = input[0].Length; 
    int[][] retVal = new int[length][]; 
    for(int x = 0; x < length; x++) 
    { 
     retVal[x] = input.Select(p => p[x]).ToArray(); 
    } 
    return retVal; 
} 
+0

感謝Tigraine,我將不得不修改我的通話功能,但沒關係 – user327764 2010-04-28 12:43:38

+0

我對此並不滿意。但用[,]枚舉器遍歷兩個維度的所有元素,這使得它更難一點。 – Tigraine 2010-04-28 13:20:09

+0

這也適用於[] []數組,我只需要修改我的調用一點使用[] [ ],但[,]雖然更容易使用。 我只是做了一點google搜索,顯然,(令我驚訝的是)[] []比[,] – user327764 2010-04-28 13:28:20