![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public static void Main()
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("type");
dt.Columns.Add("relt");
for (int i = 0; i < 4; i++)
{
DataRow dr = dt.NewRow();
dr["name"] = "name" + i;
dr["type"] = "type" + i;
dr["relt"] = "relt" + i;
dt.Rows.Add(dr);
}
DisplayTable(dt);
Console.WriteLine("\r\n =====> 进行行列转换 \r\n");
DisplayTable(ColumnToRow(dt, 0));
Console.ReadLine();
}
public static DataTable ColumnToRow(DataTable src_dt, int columnIndex) //columnIndex 用来当作新列名的列
{
DataTable dt = new DataTable();
dt.Columns.Add(src_dt.Columns[columnIndex].ColumnName);
foreach (DataRow dr in src_dt.Rows)
dt.Columns.Add(dr[columnIndex].ToString());
int n = src_dt.Columns.Count;
for (int i = 0; i < n; i++)
{
if (i == columnIndex) continue; //如果是被当作列名的列,则跳过
DataRow new_dr = dt.NewRow();
string columnName = src_dt.Columns[i].ColumnName;
new_dr[0] = columnName;
foreach (DataRow dr in src_dt.Rows)
{
string newColumnName = dr[columnIndex].ToString();
new_dr[newColumnName] = dr[columnName];
}
dt.Rows.Add(new_dr);
}
return dt;
}