c# - Pivot table with more columns -
i trying pivot list of records, came across :
public static datatable pivottable<t, tcolumn, tgrouprow, trow, tdata>( system.collections.generic.ienumerable<t> list, func<t, tcolumn> column, expression<func<t, trow>> row, func<ienumerable<t>, tdata> dataselector) { datatable table = new datatable(); var rowname = ((memberexpression)row.body).member.name; table.columns.add(new datacolumn(rowname)); var columns = list.select(column).distinct(); foreach (var col in columns) table.columns.add(new datacolumn(col.tostring())); var rows = list.groupby(row.compile()) .select(rowgroup => new { key = rowgroup.key, values = columns.groupjoin( rowgroup, c => c, r => column(r), (c, columngroup) => dataselector(columngroup)) }); foreach (var rowval in rows) { var datarow = table.newrow(); var items = rowval.values.cast<object>().tolist(); items.insert(0, rowval.key); datarow.itemarray = items.toarray(); table.rows.add(datarow); } return table; }
this solution offered post http://techbrij.com/pivot-c-array-datatable-convert-column-to-row-linq
my client code
var _datasourcematrix = //some logic datatable records var _departmentlist = //some logic datatable records var _joindatasourcedepartmentlist = in _datasourcematrix.asenumerable() join b in _departmentlist.asenumerable() on a.field<int>("entityid") equals b.field<int>("departmentid") select new { entityname = b.field<string>("name"), period = a.field<string>("period"), value = a.field<double>("value"), entityid = a.field<int>("entityid") }; _datasourcematrix = _joindatasourcedepartmentlist .orderby(x => x.period).pivottable(x => x.period, x => x.entityname, x => x.sum(y => y.value));
however, 3 columns fields : period, entityname , value utilize. wish utilize entityid well. should 1 of key group record entityname. there way modify pivottable function ?
the objective achieve should :
entityname period1, period2, period3, entityid value1 value2 value3 1 b value1 value2 value3 2
Comments
Post a Comment