我试图调整记录列表,然后我遇到了这个:
public static DataTable PivotTable<T, TColumn, TGroupRow, TRow, TData>(
this 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;
}
这是此帖http://techbrij.com/pivot-c-array-datatable-convert-column-to-row-linq
提供的解决方案我的客户端代码就像这样
var _dataSourceMatrix = //Some logic that get the DataTable records
var _departmentList = //Some logic that get the DataTable records
var _joinDataSourceDepartmentList = from a 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));
但是,这只是3列字段:可以使用Period,EntityName和Value。我也希望使用EntityID。它应该是具有EntityName的记录分组的关键之一。有没有办法修改数据透视表功能?
要实现的目标应该是这样的:
EntityName Period1, Period2, Period3, EntityID
A Value1 Value2 Value3 1
B Value1 Value2 Value3 2