转置数据表

我有下面的数据表。 我想更改数据表以将数据表转换为旁边的数据表。 我怎样才能做到这一点?

我之所以这样做是因为excel文件带来的数据如图所示,然后我想在第1行排序这些数据

当前表

|| Col 1 || Col 2 || Col 3 ____________________________________ Row 1 || 10 || 20 || 30 Row 2 || 1 || 2 || 3 

新数据表

  || Row 1 || Row 2 Col 1 || 10 || 1 Col 2 || 20 || 2 Col 3 || 30 || 3 

.NET不包含转置数据表的方法。 你必须自己做。 该网站有一个示例转置方法的教程。 我将复制并粘贴下面的代码段:

 private DataTable Transpose(DataTable dt) { DataTable dtNew = new DataTable(); //adding columns for(int i=0; i<=dt.Rows.Count; i++) { dtNew.Columns.Add(i.ToString()); } //Changing Column Captions: dtNew.Columns[0].ColumnName = " "; for(int i=0; i 

创建一个新表,其中包含与之前相反的维度,并将先前的列分配给新行,将旧行分配给新列。

例如:

 oldCol1 -> newRow1 oldCol2 -> newRow2 oldCol3 -> newRow3 oldCol4 -> newRow4 oldRow1 -> newCol1 oldCol2 -> newCol2 oldvar[a][b] -> newvar[b][a] 

并且列表继续,假设你要去

 col1 || col2 || col3 || col4 row1 ||[a][b]||[c][d]||[e][f] row2 ||[g][h]||[i][j]||[k][l] 

 row1 || col1 || col2 row2 ||[a][b]||[g][h] row3 ||[c][d]||[i][j] row4 ||[e][f]||[k][l] 
 DataTable newDt = new DataTable(); //Select indexes var indexes = dt.Rows.Cast().Select(row => dt.Rows.IndexOf(row)); //Select the columns var newCols = indexes.Select(i => "Row" + i); //Add columns foreach(var newCol in newCols) { newDt.Add(newCol); } //Select rows var newRows = dt.Rows.Cast().Select(col => { row = newDt.NewRow(); foreach(int i in indexes) { row[i] = dt.Rows[i][col.Name]; } return row; }); //Add row to new datatable foreach(var row in newRows) { newDt.Add(row); }