Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

c# - Transpose a datatable

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 like o do this is because the excel file brings the data in like shown and then i would like to sort this data out on Row 1

Current table

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

New Datatable

      || Row 1 || Row 2 
Col 1 ||  10   ||   1
Col 2 ||  20   ||   2
Col 3 ||  30   ||   3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.NET does not include a method to transpose data tables. You have to make your own. This website has a tutorial on an example transpose method. I will copy and paste the code snippet below:

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<dt.Rows.Count; i++) 
     {
      //For dateTime columns use like below
       dtNew.Columns[i+1].ColumnName = Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
      //Else just assign the ItermArry[0] to the columnName prooperty
     }

    //Adding Row Data
    for(int k=1; k<dt.Columns.Count; k++)
    {
        DataRow r = dtNew.NewRow();
        r[0] = dt.Columns[k].ToString(); 
        for(int j=1; j<=dt.Rows.Count; j++)
        r[j] = dt.Rows[j-1][k];  
        dtNew.Rows.Add(r);
    }

 return dtNew;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...