我有以下输入数据:
type name dept salary
senior ABC 123 2000
junior ABC 456 1000
senior IJK 456 3000
senior LMN 123 2000
junior LMN 123 1500
senior STQ 123 2000
我希望跟随旋转输出:
name dept junior_salary senior_salary
ABC 123 0 2000
ABC 456 1000 0
IJK 456 0 3000
LMN 123 1500 2000
STQ 123 0 2000
以下是我写的LINQ代码:
List<Posting> posting = getData();
posting.GroupBy(x=>new{x.type, x.name, x.dept})
.Select(x=>new {
name = x.Key.name,
dept = x.Key.dept,
junior_salary = x.Where(z=>x.Key.type=="junior").Sum(y=>y.salary),
senior_salary = x.Where(z=>x.Key.type=="senior").Sum(y=>y.salary)
}).ToList();
这给了我不正确的结果。以下是我得到的结果
name dept junior_salary senior_salary
ABC 123 0 2000
ABC 456 1000 0
IJK 456 0 3000
LMN 123 0 2000
LMN 123 1500 0
STQ 123 0 2000
这是我为运行示例创建的小提琴: https://dotnetfiddle.net/QCbyyD
需要帮助。
答案 0 :(得分:1)
var pivotList = posting.GroupBy(x=>new{x.name, x.dept})
.Select(x=>new {
name = x.Key.name,
dept = x.Key.dept,
junior_salary = x.Where(z=>z.type == "junior").Sum(y=>y.salary),
senior_salary = x.Where(z=>z.type == "senior").Sum(y=>y.salary)
}).ToList();
修复是从group by子句中删除类型。
答案 1 :(得分:1)
这就是你需要的:
var pivotList =
posting
.GroupBy(x => new { x.name, x.dept })
.Select(x => new
{
name = x.Key.name,
dept = x.Key.dept,
junior_salary = x.Where(z => z.type == "junior").Sum(y => y.salary),
senior_salary = x.Where(z => z.type == "senior").Sum(y => y.salary)
})
.ToList();
您不应该按type
分组。