我在下面的链接中使用扩展方法来旋转数据:
https://techbrij.com/pivot-c-array-datatable-convert-column-to-row-linq

我包含来自链接的代码,以防万一将来有人发现此问题并且链接失效:

public static DataTable ToPivotTable<T, TColumn, TRow, TData>(
    this IEnumerable<T> source,
    Func<T, TColumn> columnSelector,
    Expression<Func<T, TRow>> rowSelector,
    Func<IEnumerable<T>, TData> dataSelector)
        {
            DataTable table = new DataTable();
            var rowName = ((MemberExpression)rowSelector.Body).Member.Name;
            table.Columns.Add(new DataColumn(rowName));
            var columns = source.Select(columnSelector).Distinct();

            foreach (var column in columns)
                table.Columns.Add(new DataColumn(column.ToString()));

            var rows = source.GroupBy(rowSelector.Compile())
                             .Select(rowGroup => new
                             {
                                 Key = rowGroup.Key,
                                 Values = columns.GroupJoin(
                                     rowGroup,
                                     c => c,
                                     r => columnSelector(r),
                                     (c, columnGroup) => dataSelector(columnGroup))
                             });

            foreach (var row in rows)
            {
                var dataRow = table.NewRow();
                var items = row.Values.Cast<object>().ToList();
                items.Insert(0, row.Key);
                dataRow.ItemArray = items.ToArray();
                table.Rows.Add(dataRow);
            }

            return table;
        }

引用链接中的示例,您将获得数据透 View ,例如:
var pivotTable = data.ToPivotTable(
              item => item.Year,
              item => item.Product,
              items => items.Any() ? items.Sum(x=>x.Sales) : 0);

我的问题是,如何在此查询中包含更多行以返回例如ProductCode呢?item => new {item.Product, item.ProductCode}不起作用。

==============编辑/2018年10月23日==============

假设我的数据是这个;

c# - 在数据透视中包含更多行-LMLPHP

在上述代码的帮助下,我可以设法做到这一点;
c# - 在数据透视中包含更多行-LMLPHP

我想要实现的是(额外列:STOCKID或任何其他列);
c# - 在数据透视中包含更多行-LMLPHP

最佳答案

匿名类型不能作为通用参数传递。尝试将枢轴键定义为结构:

public struct PivotKey
{
    public string Product;
    public int ProductCode; // assuming your product codes are integers
}

这样,就所有字段的相等性和哈希码而言,您可以利用struct的默认EqualsGetHashCode方法实现。

然后,如下定义rowSelector:
item => new PivotKey { Product = item.Product, ProductCode = item.ProductCode}

07-24 18:45
查看更多