简体   繁体   中英

c# DataTable pivote

I have datatable with the below structure and I want to pivot it without any calculation like the one beneath it any ideas

Category Week Resulton
cat1     w1   26
cat2     w1   50
cat3     w1   54
cat4     w1   19
cat1     w2   54
cat2     w2   31
cat3     w2   36
cat4     w2   25
cat1     w3   21
cat2     w3   44
cat3     w3   36
cat4     w3   38
cat1     w4   24
cat2     w4   39
cat3     w4   24
cat4     w4   28



week cat1 cat2 cat3 cat4
w1   26   50   54   19
w2   54   31   36   25
w3   21   44   36   38
w4   24   39   24   28

You can easily get desired result with free NReco PivotData library:

DataTable t; // assume this is table with "Category","Wee","Resolution" columns
var pivotData = new PivotData(
    new string[] {"Category","Week"},
    new SumAggregatorFactory("Resolution"),
    new DataTableReader(t) );
var pivotTable = new PivotTable(
    new []{"Week"}, // row dimension(s)
    new []{"Category"}, // column dimension(s)
    pivotData );
// use pivotTable to access calculated values:
var rowLabels = pivotTable.RowKeys;
var colLabels = pivotTable.ColumKeys;
var cellValue = pivotTable[0, 0].Value; // w1 x cat1 => 26

I'm an author of this library; feel free to ask any questions if something is not clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM