交换DataTable中的行列位置

比如我们在数据库中取出的数据放到DataTable中如下:

标题 列一 列二 列三
行一 34 23 65
行二 67 56 89

 

行列交换后得到的数据为:

标题 行一 行二
列一 34 67
列二 23 56
列三 65 89


下面是交换的函数,代码如下:

private DataTable SwapDTCR(DataTable inputDT)
        {
            DataTable outputDT = new DataTable();

            //标题的位置不变
            outputDT.Columns.Add(inputDT.Columns[0].ColumnName.ToString());
            
            foreach (DataRow inRow in inputDT.Rows)
            {
                string newColName = inRow[0].ToString();
                outputDT.Columns.Add(newColName);
            }
                
            for (int rCount = 1; rCount <= inputDT.Columns.Count - 1; rCount++)
            {
                DataRow newRow = outputDT.NewRow();
               
                newRow[0] = inputDT.Columns[rCount].ColumnName.ToString();
                for (int cCount = 0; cCount <= inputDT.Rows.Count - 1; cCount++)
                {
                    string colValue = inputDT.Rows[cCount][rCount].ToString();
                    newRow[cCount + 1] = colValue;
                }
                outputDT.Rows.Add(newRow);
            }
            return outputDT;
        }
posted @ 2010-09-03 14:29  绿森林  阅读(1305)  评论(1编辑  收藏  举报