Transpose a datatable

后端 未结 3 718
情话喂你
情话喂你 2020-12-22 08:31

I have the data table below. I would like to change the data table to transform the data table into the one next to it. How can I do this?

The reason why i would lik

3条回答
  •  心在旅途
    2020-12-22 09:28

    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);
    }
    

提交回复
热议问题