2012-07-24 54 views
0

我有一個程序,執行長時間處理。第一步是將表格從XML格式轉換爲2維數組(arr [,])。之後,許多步驟都會執行,只有在他們之後,我才知道表格是否具有行標題或列標題。爲了明確這一點,行標題意味着表所示:c# - 如何反轉二維數組

Name city id 
Anna  NY  1 
Joe  NJ  2 

列標題是指:

Name Anna  Joe 
City NY  NJ 
id  1  2 

該表是根據標題處理。我採取與某些標題有關的價值觀並對其進行研究。我正在尋找一種方式來表示一種方式,所以我不應該每次檢查表類型是行還是列。我想避免類似以下代碼:

List<Cell> cells; 
if (tableType == rows) 
    cells = table.getCol("Name"); 
else 
    cells = table.getRow("Name") 

我很樂意提供任何建議。

謝謝!

+0

如果你有一個二維數組,你將有可能是一個嵌套的for循環。反循環。或者澄清你的問題。 – 2012-07-24 12:34:00

+1

你有什麼試過的?這應該是一些簡單的代碼,包含循環和一些索引計算。 – 2012-07-24 12:34:28

+0

你需要的是所謂的Pivoting。 http://stackoverflow.com/questions/3687708/pivoting-a-collection-of-arrays – 2012-07-24 12:34:29

回答

0

有來自This Question

int[,] array = new int[4,4] { 
    { 1,2,3,4 }, 
    { 5,6,7,8 }, 
    { 9,0,1,2 }, 
    { 3,4,5,6 } 
}; 

int[,] rotated = RotateMatrix(array, 4); 

static int[,] RotateMatrix(int[,] matrix, int n) { 
    int[,] ret = new int[n, n]; 

    for (int i = 0; i < n; ++i) { 
     for (int j = 0; j < n; ++j) { 
      ret[i, j] = matrix[j, i]; 
     } 
    } 

    return ret; 
} 
+0

OP想要換位,就我所見,所以'ret [i,j] = matrix [j,i] ;'。 – 2012-07-24 12:36:40

+0

@DanielFischer who y y right,現在編輯 – 2012-07-24 12:38:37

0

採取了一些漂亮的代碼有一個這就是所謂的替代和table.getRow方法,然後調用它們。

喜歡的東西:

static bool IsColumns = true; 
List<Cell> Get(string input) 
{ 
    if (IsColumns) return table.getCol(input); 
    else return table.getRow(input); 
}