动态枢轴 Linq C#

4
我有以下的集合/表格。
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中硬编码该值。


使用LINQ进行数据透视 - Magnus
1
“the details are dynamic” 您指的是什么意思? - dtb
我的意思是,表格随时可能添加新的细节,因此Linq必须将新的细节作为列包含进去。 - stillsmallvoice
可能是使用LINQ旋转数据是否可能?的重复问题。 - nawfal
1个回答

2

使用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

谢谢您的回复!我正在处理您的查询,以便最终输出一个可以绑定到GridView的源,就像我的示例一样。 - stillsmallvoice
你知道有什么简单的方法可以做到这一点吗,Charles?我想我可以在你那里的for each语句中创建一个datatable。 - stillsmallvoice
如果您想在添加更多详细值时避免更改UI控件,那么是的,您将不得不动态创建您的控件。您可以查看“Aggregate”方法并将new GridView()作为种子传递,并在其中构建它。这可能比使用循环更容易。http://msdn.microsoft.com/en-us/library/bb549218.aspx - Charles Lambert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接