Dynamic PIVOT using C# Linq

前端 未结 2 540
灰色年华
灰色年华 2020-12-05 22:39

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

相关标签:
2条回答
  • 2020-12-05 23:10

    Here is the code with the compilation errors corrected:

    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;
    }
    

    I 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.

    0 讨论(0)
  • Good one., but you might want to replace the below line

     .ForEach (c => result.Columns.Add(c, pivotColumn.DataType));
    

    with this (change pivotColumn to pivotValue)

     .ForEach (c => result.Columns.Add(c, pivotValue.DataType));
    

    Works perfectly for my requirement.

    0 讨论(0)
提交回复
热议问题