-1

I have a datatable in the following form

Country Currency    Category    Value (Delivered)
AFRICA  USD         CONTAINER   100
AFRICA  USD         CONTAINER   100
AFRICA  USD         PLASTIC     100 
AFRICA  USD         PLASTIC     100 
AFRICA  USD         PLASTIC     100 
AFRICA  USD         PLASTIC     100 
AFRICA  USD         PLASTIC     100
AFRICA  USD         PLASTIC     100

I need to get the values as below,

COUNTRY Currency    CONTAINER   PLASTIC     OTHERS
Africa  USD         200         600          0

Means, anything other than plastic or container, need to be added in others column.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Rosario
  • 21
  • 5
  • Using LINQ: http://stackoverflow.com/questions/12866685/dynamic-pivot-using-c-sharp-linq – Thirisangu Ramanathan Jun 10 '15 at 04:26
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jun 10 '15 at 05:50

1 Answers1

0

You can use NReco.PivotData nuget package for this purpose:

DataTable tbl;  // lets assume this is your datatable
var pvtData = new PivotData(new[] {"Country", "Currency", "Category"}, new SumAggregatorFactory("Value (Delivered)") );
pvtData.ProcessData(new DataTableReader(tbl));
var pvtTbl = new PivotTable(
    new [] {"Country", "Currency"}, //rows
    new [] {"Category"}, //columns
    pvtData);

// use PivotTable class API to iterate through rows/columns and get the values
for (var r=0; r<pvtTbl.RowKeys.Length; r++) { 
    var rowKey = pvtTbl.RowKeys[r];
    for (var c=0; c<pvtTbl.ColumnKeys.Length; c++) {
        var cellValue = pvtTbl[r,c].Value;
        // do what you need: render HTML table, or export to CSV, or populate pivoted DataTable
    }
}

Library is free for single-deployment non-SaaS projects (I'm the author of this lib).

Vitaliy Fedorchenko
  • 8,447
  • 3
  • 37
  • 34