从数据表中旋转值
本文关键字:旋转 数据表 | 更新日期: 2023-09-27 17:55:08
>我有一个以下形式的数据表
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
我需要获取如下值,
COUNTRY Currency CONTAINER PLASTIC OTHERS
Africa USD 200 600 0
意味着,除了塑料或容器之外的任何内容都需要添加到其他列中。
您可以使用 NReco.PivotData nuget 包来实现此目的:
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
}
}
库对单部署非 SaaS 项目是免费的(我是这个库的作者)。