使用Linq进行通用分组

时间:2014-08-28 12:02:41

标签: linq grouping pivot-table

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

我需要将此平面表转换为交叉布置表,就像这样

EmployeeName    EmployeeNumber      Housing  Tickets  Transportation  

ABDEL           002285              100.00   12.083   100.00  
MOHAMED         001546              0.000    150.00   0.935

1 个答案:

答案 0 :(得分: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),
    });