转置函数,ATable转置为BTable,再次转置将恢复为ATable
static DataTable GetTransposeDataTable(DataTable sourceDataTable)
{
DataTable newDataTable = new DataTable();
for (int i = 0; i < sourceDataTable.Rows.Count; i++)
{
newDataTable.Columns.Add("Column" + i, typeof(string));
}
foreach (DataColumn dc in sourceDataTable.Columns)
{
DataRow drNew = newDataTable.NewRow();
for (int i = 0; i < sourceDataTable.Rows.Count; i++)
{
drNew[i] = sourceDataTable.Rows[i][dc].ToString();
}
newDataTable.Rows.Add(drNew);
}
return newDataTable;
}
测试
源数据表格式:
A A A A ?
A B C D ?
B B B B ?
A B C D ?
C C D D ?
A D A B ?
D D C A ?
C D C D ?
A B C D ?
A B C D ?
转置完成后的数据表格式:
A A B A C A D C A A
A B B B C D D D B B
A C B C D A C C C C
A D B D D B A D D D
? ? ? ? ? ? ? ? ? ?
再次转置后数据表格式:
A A A A ?
A B C D ?
B B B B ?
A B C D ?
C C D D ?
A D A B ?
D D C A ?
C D C D ?
A B C D ?
A B C D ?