C#LINQ在表上旋转
我有以下输入数据:C#LINQ在表上旋转,c#,linq,C#,Linq,我有以下输入数据: 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 junio
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();
下面是我为运行示例而创建的小提琴:
我需要帮助
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();
修复方法是从GROUPBY子句中删除类型 这就是您需要的:
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();
您不应该按
类型分组
不正确的结果?您希望我们对该语句做什么?您不需要进行名称检查,因为您是根据名称分组的,组中的所有值都将与键中的名称匹配。此外,还应指定修复程序从分组中删除类型。
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();