在Pivot中包含更多行

Kem*_*min 7 c# linq lambda

我在下面的链接中使用扩展方法来转移我的数据: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;
        }
Run Code Online (Sandbox Code Playgroud)

参考链接中的示例,您将获得数据透视图;

var pivotTable = data.ToPivotTable(
              item => item.Year, 
              item => item.Product,  
              items => items.Any() ? items.Sum(x=>x.Sales) : 0);
Run Code Online (Sandbox Code Playgroud)

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


============== EDIT/2018年10月23日==============


假设我的数据是这样的;

在此输入图像描述

借助上述代码,我可以设法做到这一点; 在此输入图像描述

我想要实现的是这个(额外的col:STOCKID或任何其他cols); 在此输入图像描述

Joh*_*van 1

示例: https: //dotnetfiddle.net/mXr9sh

问题似乎是从表达式中获取行名称,因为它仅设计用于处理一行。这可以通过这个函数来解决:

public static IEnumerable<string> GetMemberNames<T1, T2>(Expression<Func<T1, T2>> expression)
{
    var memberExpression = expression.Body as MemberExpression;
    if (memberExpression != null) 
    {
        return new[]{ memberExpression.Member.Name };
    }
    var memberInitExpression = expression.Body as MemberInitExpression;
    if (memberInitExpression != null)
    {
        return memberInitExpression.Bindings.Select(x => x.Member.Name);
    }
    var newExpression = expression.Body as NewExpression;
    if (newExpression != null)
    {
        return newExpression.Arguments.Select(x => (x as MemberExpression).Member.Name);
    }

    throw new ArgumentException("expression"); //use: `nameof(expression)` if C#6 or above
}
Run Code Online (Sandbox Code Playgroud)

一旦你有了这个函数,你就可以替换这些行:

var rowName = ((MemberExpression)rowSelector.Body).Member.Name;
table.Columns.Add(new DataColumn(rowName));
Run Code Online (Sandbox Code Playgroud)

有了这个:

var rowNames = GetMemberNames(rowSelector);
rowNames.ToList().ForEach(x => table.Columns.Add(new DataColumn(x)));
Run Code Online (Sandbox Code Playgroud)

这种方法的一个缺点是这些列的各种值在单个列中串联返回;所以你需要从字符串中提取数据。


结果数据表:

(显示为 JSON)

[
  {
    "StockId": "{ StockId = 65, Name = Milk }",
    "Name": "3",
    "Branch 1": "1",
    "Branch 2": "0",
    "Central Branch": null
  },
  {
    "StockId": "{ StockId = 67, Name = Coffee }",
    "Name": "0",
    "Branch 1": "0",
    "Branch 2": "22",
    "Central Branch": null
  }
]
Run Code Online (Sandbox Code Playgroud)

完整代码清单

using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using Newtonsoft.Json; //just for displaying output

public class Program 
{
    public static void Main()
    {
        var data = new[] { 
            new { StockId = 65, Name = "Milk", Branch = 23, BranchName = "Branch 1", Stock = 3 },
            new { StockId = 65, Name = "Milk", Branch = 24, BranchName = "Branch 2", Stock = 1 },
            new { StockId = 67, Name = "Coffee", Branch = 22, BranchName = "Central Branch", Stock = 22 }
        };

        var pivotTable = data.ToPivotTable(
            item => item.BranchName, 
            item => new {item.StockId, item.Name},  
            items => items.Any() ? items.Sum(x=>x.Stock) : 0);

        //easy way to view our pivotTable if using linqPad or similar
        //Console.WriteLine(pivotTable);
        //if not using linqPad, convert to JSON for easy display
        Console.WriteLine(JsonConvert.SerializeObject(pivotTable, Formatting.Indented));
    }
}   

public static class PivotExtensions
{
    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();
        //foreach (var row in rowSelector()
        var rowNames = GetMemberNames(rowSelector);
        rowNames.ToList().ForEach(x => table.Columns.Add(new DataColumn(x)));
        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;
    }
    public static IEnumerable<string> GetMemberNames<T1, T2>(Expression<Func<T1, T2>> expression)
    {
        var memberExpression = expression.Body as MemberExpression;
        if (memberExpression != null) 
        {
            return new[]{ memberExpression.Member.Name };
        }
        var memberInitExpression = expression.Body as MemberInitExpression;
        if (memberInitExpression != null)
        {
            return memberInitExpression.Bindings.Select(x => x.Member.Name);
        }
        var newExpression = expression.Body as NewExpression;
        if (newExpression != null)
        {
            return newExpression.Arguments.Select(x => (x as MemberExpression).Member.Name);
        }

        throw new ArgumentException("expression"); //use: `nameof(expression)` if C#6 or above
    }

}
Run Code Online (Sandbox Code Playgroud)