2012-01-18 81 views
3

我有以下的集合/表动态透视LINQ的C#

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中的值。

+0

[使用LINQ的数据透视数据](http://stackoverflow.com/questi ons/963491/pivot-data-using-linq) – Magnus 2012-01-18 16:47:31

+1

“细节是动态的”是什么意思? – dtb 2012-01-18 16:47:49

+0

我的意思是可以随时添加一个新的细节到表中,所以linq将不得不包含新的细节作为列 – stillsmallvoice 2012-01-18 16:53:09

回答

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 
+0

感谢您的回应!我正在处理您的查询,最终输出将绑定到gridview的源代码,如我的示例中所示。 – stillsmallvoice 2012-01-18 17:58:36

+0

你知道一个简单的方法来做到这一点查尔斯?我想我可以在其中为每个语句创建一个数据表。 – stillsmallvoice 2012-01-18 18:27:53

+0

如果您在添加更多细节值时避免更改UI控件,那么是的,您将不得不动态创建控件。你可以看看'Aggregate'方法,并传入一个新的GridView()'作为种子,并在那里构建它。这可能比使用循环更容易。 http://msdn.microsoft.com/en-us/library/bb549218.aspx – 2012-01-18 18:53:03