将DataTable行列转换

 

    /// <summary>

    /// 将DataTable行列转换

    /// </summary>

    /// <param name="src">要转换的DataTable</param>

    /// <param name="columnHead">要作为Column的哪列</param>

    /// <returns></returns>

    public DataTable Col2Row(DataTable src, int columnHead)

    {

        DataTable result = new DataTable();

        DataColumn myHead = src.Columns[columnHead];

        result.Columns.Add(myHead.ColumnName);

        for (int i = 0; i < src.Rows.Count; i++)

        {

            result.Columns.Add(src.Rows[i][myHead].ToString());

        }

        //

        foreach (DataColumn col in src.Columns)

        {

            if (col == myHead)

                continue;

            object[] newRow = new object[src.Rows.Count + 1];

            newRow[0] = col.ColumnName;

            for (int i = 0; i < src.Rows.Count; i++)

            {

                newRow[i + 1] = src.Rows[i][col];

            }

            result.Rows.Add(newRow);

        }

        return result;

    }

 

你可能感兴趣的:(Datatable)