Dynamic PIVOT using C# Linq
NickName:niklodeon Ask DateTime:2012-10-13T04:33:31

Dynamic PIVOT using C# Linq

I am trying to use following code to create the PIVOT but its not working.

It's giving me compile time error. I don't know linq so unable to use it.

Please help :

   DataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {
    // find primary key columns 
    //(i.e. everything but pivot column and pivot value)
    DataTable temp = dt.Copy();
    temp.Columns.Remove( pivotColumn.ColumnName );
    temp.Columns.Remove( pivotValue.ColumnName );
    string[] pkColumnNames = temp.Columns.Cast(<DataColumn>)
        .Select( c => c.ColumnName )
        .ToArray();

    // prep results table
    DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();
    result.PrimaryKey = result.Columns.Cast(<DataColumn>).ToArray();
    dt.AsEnumerable()
        .Select(r =>; r[pivotColumn.ColumnName].ToString())
        .Distinct().ToList()
        .ForEach (c => result.Columns.Add(c, pivotColumn.DataType));

    // load it
    foreach( DataRow row in dt.Rows ) {
        // find row to update
        DataRow aggRow = result.Rows.Find(
            pkColumnNames
                .Select( c => row[c] )
                .ToArray() );
        // the aggregate used here is LATEST 
        // adjust the next line if you want (SUM, MAX, etc...)
        aggRow[row[pivotColumn.ColumnName].ToString()] = row[pivotValue.ColumnName];
    }

    return result;
}

Code from : http://michaeljswart.com/2011/06/forget-about-pivot/

Moreover it tried to use following code, it works well except for it is not giving total sum for Value Column

public DataTable GetInversedDataTable(DataTable table, string columnX, string columnY, string columnZ, string nullValue, bool sumValues)
        {
            //Create a DataTable to Return
            DataTable returnTable = new DataTable();

            DataTable tempTable = table.Clone();

            if (string.IsNullOrEmpty(columnX))
            {
                columnX = table.Columns[0].ColumnName;
            }

            tempTable.Columns.Remove(columnX);


            //Add a Column at the beginning of the table
            //returnTable.Columns.Add(columnY);

            returnTable = tempTable.Clone();

            //Read all DISTINCT values from columnX Column in the provided DataTale
            List<string> columnXValues = new List<string>();


            foreach (DataRow dr in table.Rows)
            {
                string columnXTemp = dr[columnX].ToString();
                if (!columnXValues.Contains(columnXTemp))
                {
                    //Read each row value, if it's different from others provided, add to the list of values and creates a new Column with its value.
                    columnXValues.Add(columnXTemp);
                    returnTable.Columns.Add(columnXTemp);
                }
            }

            //Verify if Y and Z Axis columns re provided
            if (!string.IsNullOrEmpty(columnY) && !string.IsNullOrEmpty(columnZ))
            {
                //Read DISTINCT Values for Y Axis Column
                List<string> columnYValues = new List<string>();

                foreach (DataRow dr in table.Rows)
                {
                    if (!columnYValues.Contains(dr[columnY].ToString()))
                    {
                        columnYValues.Add(dr[columnY].ToString());
                    }
                }

                //Loop all Column Y Distinct Value
                foreach (string columnYValue in columnYValues)
                {
                    //Creates a new Row
                    DataRow drReturn = returnTable.NewRow();
                    drReturn[0] = columnYValue;
                    //foreach column Y value, The rows are selected distincted
                    DataRow[] rows = table.Select((columnY + "='") + columnYValue + "'");

                    //Read each row to fill the DataTable
                    foreach (DataRow dr in rows)
                    {
                        string rowColumnTitle = dr[columnX].ToString();

                        //Read each column to fill the DataTable
                        foreach (DataColumn dc in returnTable.Columns)
                        {
                            if (dc.ColumnName == rowColumnTitle)
                            {
                                //If Sum of Values is True it try to perform a Sum
                                //If sum is not possible due to value types, the value displayed is the last one read
                                if (sumValues)
                                {
                                    try
                                    {
                                        drReturn[rowColumnTitle] = Convert.ToDecimal(drReturn[rowColumnTitle]) + Convert.ToDecimal(dr[columnZ]);
                                    }
                                    catch
                                    {
                                        drReturn[rowColumnTitle] = dr[columnZ];
                                    }
                                }
                                else
                                {
                                    drReturn[rowColumnTitle] = dr[columnZ];

                                }
                            }
                        }
                    }

                    returnTable.Rows.Add(drReturn);

                }
            }
            else
            {
                throw new Exception("The columns to perform inversion are not provided");
            }

            //if a nullValue is provided, fill the datable with it
            if (!string.IsNullOrEmpty(nullValue))
            {
                foreach (DataRow dr in returnTable.Rows)
                {
                    foreach (DataColumn dc in returnTable.Columns)
                    {
                        if (string.IsNullOrEmpty(dr[dc.ColumnName].ToString()))
                        {
                            dr[dc.ColumnName] = nullValue;
                        }
                    }
                }
            }

            return returnTable;
        }

GetInversedDataTable(dtNormal, "Dated", "OrderStatus", "Qty", " ", true);

Please help :)

Copyright Notice:Content Author:「niklodeon」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12866685/dynamic-pivot-using-c-sharp-linq

Answers
Risky Martin 2012-10-13T03:37:51

Here is the code with the compilation errors corrected:\n\nDataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {\n // find primary key columns \n //(i.e. everything but pivot column and pivot value)\n DataTable temp = dt.Copy();\n temp.Columns.Remove( pivotColumn.ColumnName );\n temp.Columns.Remove( pivotValue.ColumnName );\n string[] pkColumnNames = temp.Columns.Cast<DataColumn>()\n .Select( c => c.ColumnName )\n .ToArray();\n\n // prep results table\n DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();\n result.PrimaryKey = result.Columns.Cast<DataColumn>().ToArray();\n dt.AsEnumerable()\n .Select(r => r[pivotColumn.ColumnName].ToString())\n .Distinct().ToList()\n .ForEach (c => result.Columns.Add(c, pivotColumn.DataType));\n\n // load it\n foreach( DataRow row in dt.Rows ) {\n // find row to update\n DataRow aggRow = result.Rows.Find(\n pkColumnNames\n .Select( c => row[c] )\n .ToArray() );\n // the aggregate used here is LATEST \n // adjust the next line if you want (SUM, MAX, etc...)\n aggRow[row[pivotColumn.ColumnName].ToString()] = row[pivotValue.ColumnName];\n }\n\n return result;\n}\n\n\nI changed Cast(<DataColumn>) to Cast<DataColumn>() in two locations and got rid of the semicolon in the middle of a lambda expression. The second part of your question is a little trickier. You may want to ask it as its own question.",


More about “Dynamic PIVOT using C# Linq” related questions

Using CTE with a dynamic pivot

I'm trying to use This question to perform a dynamic pivot, but I want to use a CTE to get the initial data. My query looks like this: DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);

Show Detail

INSERT INTO Temp Table Dynamic Pivot

I've the following t-sql: select d.OutageType + '/' + e.Facility Outage, c.MaterialScopeCode, count(a.ItemNo) CountofItemNo into #tt from _OutageMateria...

Show Detail

Dynamic Pivot SSIS

I need to prepare a dynamic pivot in SSIS. I can create it in SQL Server itself without using pivot component of ssis. But how it can be exported to Excel Destination is my problem. The number of c...

Show Detail

EPPlus: dynamic pivot table using external connection

I'm using EPPlus to generate an Excel workbook from C#. I read that EPPlus is supporting pivot tables, but I would need something like the Excel-interop property PivotTable.SourceData, to generate a

Show Detail

Pivot using Dynamic SQL statement

This is a small sample of the data. In the actual data, the values under Name and Code are in the hundreds and those values change frequently. For this reason, hard-coding the Pivot statement will...

Show Detail

Dynamic Pivot with CTE

I was trying to create a Common Table Express(CTE) to store some data that I need which requires a bunch of inner join. Then, I would like to pivot the result using dynamic pivot columns. I wrot...

Show Detail

How to export dynamic SQL Server pivot table to excel

I'm working on a webapp that displays data from a Microsoft SQL Server dynamic pivot table. Normally I'd try and figure out a way to do the dynamic pivot in c#, but in this case the pivot has to b...

Show Detail

SQL Pivot Table dynamic

I've tried so hard to understand how to create a pivot table in SQL, but I can't manage it! I have the following columns: link_id route_section date_1 StartHour AvJT data_source ......

Show Detail

Passing dynamic Columns to Pivot in Oracle

I am new to oracle, I am trying to pass the dynamically generated column names to pivot in oracle using the below query DECLARE v_cols VARCHAR2(100); v_query VARCHAR2(4000); BEGIN SELECT

Show Detail

Prefix column names when using dynamic Pivot

So I am working on a way to report some data from a table that tracks patients response to questions about chest pain when they visit the emergency room. When patients arrive to the ER they are ask...

Show Detail