2014-08-28 38 views
0
EmployeeName EmployeeNumber AllowanceName Amount 

ABDEL   002285   Housing   100.00 
ABDEL   002285   Tickets   12.083 
ABDEL   002285   Transportation 100.00 
MOHAMED   001546   Tickets   150.00 
MOHAMED   001546   Transportation 0.935 

我需要这个平表转换成交叉表的表是这样的通用分组使用LINQ

EmployeeName EmployeeNumber  Housing Tickets Transportation 

ABDEL   002285    100.00 12.083 100.00 
MOHAMED   001546    0.000 150.00 0.935 
+0

你是如何最终显示此?有一些UI和报告控件比Linq更能动态地处理数据透视表。 – 2014-08-28 12:42:49

+0

您应该规范化该表。 'AllowanceName'应该是另一个表的外键。 – 2014-08-28 13:01:12

回答

0

不是真的一般,但也许足够了:

var query = empmloyee 
    .GroupBy(x => new { x.EmployeeName, x.EmployeeNumber }) 
    .Select(gx => new { 
     EmployeeName = gx.Key.EmployeeName, 
     EmployeeNumber = gx.Key.EmployeeNumber, 
     Housing  = gx.Where(x => x.AllowanceName == "Housing") 
          .Sum(x => x.Amount), 
     Tickets  = gx.Where(x => x.AllowanceName == "Tickets") 
          .Sum(x => x.Amount), 
     Transportation = gx.Where(x => x.AllowanceName == "Transportation") 
          .Sum(x => x.Amount), 
    });