Dynamic Pivot Linq C#

本文关键字:Linq Pivot Dynamic | 更新日期: 2023-09-27 18:20:45

我有以下集合/表

Category    Type       Detail     Cost
Auto        Hybrid     AC         80
Auto        Hybrid     Sunroof    100
Auto        Standard   AC         120
Motorcycle  Standard   Radio      60

linq有没有办法让它变成这样?

Category     Type      AC     Radio    Sunroof     
Auto         Hybrid    80     0        100 
Auto         Standard  120    0        0
Motorcycle   Standard  0      60       0

细节是动态的,所以我不能硬编码linq中的值。

Dynamic Pivot Linq C#

使用let关键字生成用于group by子句的密钥,如下所示:

var query = from item in list
            let key = new { Category = item.Category, Type = item.Type }
            group new { Detail = item.Detail, Cost = item.Cost } by key;

您可以循环查询返回的项目,如下所示:

foreach(var item in query) {
    Console.WriteLine("{0} {1}: ", item.Key.Category, item.Key.Type);
    foreach(var detail in item) {
        Console.WriteLine("'t{0} {1}", detail.Detail, detail.Cost);
    }
}

它显示以下输出

Auto Hybrid:
        AC 80
        Sunroof 100
Auto Standard:
        AC 120
Motorcycle Standard:
        Radio 60