Cross-table row-to-column Conversion Method

Source: Internet
Author: User

/// <Summary>
/// Convert the value of the second column of datatable into a column (convert the original row table to a cross table. If no corresponding value exists, the default value is "0 ")
/// </Summary>
/// <Param name = "DT"> three columns are required, and the third column is the value. </param>
/// <Returns> </returns>
Public static datatable getcrosstable (datatable DT)
{
If (Dt = NULL | DT. Columns. Count! = 3 | DT. Rows. Count = 0)
{
Return DT;
}
Else
{
Datatable result = new datatable ();
Result. Columns. Add (Dt. Columns [0]. columnname );
Datatable dtcolumns = DT. defaultview. totable ("dtcolumns", true, DT. Columns [1]. columnname );
For (INT I = 0; I <dtcolumns. Rows. Count; I ++)
{
String colname;
If (dtcolumns. Rows [1] [0] Is datetime)
{
Colname = convert. todatetime (dtcolumns. Rows [I] [0]). tostring (constants. date_formart );
}
Else
{
Colname = dtcolumns. Rows [I] [0]. tostring ();
}
Result. Columns. Add (colname );
Result. Columns [I + 1]. defaultvalue = "0 ";
}
Datarow drnew = result. newrow ();
Drnew [0] = DT. Rows [0] [0];
String rowname = drnew [0]. tostring ();
Foreach (datarow DR in DT. Rows)
{
String colname = Dr [1]. tostring ();
Double dvalue = math. Round (getdoublevalue (Dr [2], 0), 2 );
If (Dr [0]. tostring (). Equals (rowname, stringcomparison. currentcultureignorecase ))
{
Drnew [colname] = dvalue. tostring ();
}
Else
{
Result. Rows. Add (drnew );
Drnew = result. newrow ();
Drnew [0] = Dr [0];
Rowname = drnew [0]. tostring ();
Drnew [colname] = dvalue. tostring ();
}
}
Result. Rows. Add (drnew );
Return result;
}
}
Log on to http: // 121.18.78.216/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.