将行数据转换为Linq中的列

时间:2017-02-10 07:09:37

标签: c# linq

我在变量“Result”中有数据,如下所示

StaffName   ProjectName    Month      Weeks
Venkat      Project1       January    4
Venkat      Project1       February   2
Venkat      Project2       January    3
Kumar       Project1       March      5
Kumar       Project4       December   3

现在我想要下面的输出

StaffName   ProjectName   Jan   Feb  Mar  Dec   Total
Venkat       Project1      4     2               6
Venkat       Project2      3                     3
Kumar        Project1                 5          5
Kumar        Project4                      3     3

如果您有任何想法,请帮助我

1 个答案:

答案 0 :(得分:1)

我认为你想以动态的方式去做,但没有简单的方法。

所以只需使用GroupBy,卢克。像这样:

var res = data.GroupBy(x => new { x.StaffName, x.ProjectName })
    .Select(x => new
    {
        StaffName = x.Key.StaffName,
        ProjectName = x.Key.ProjectName,
        Jan = x.Where(y => y.Month == "January").Sum(y => y.Weeks),
        Feb = x.Where(y => y.Month == "February").Sum(y => y.Weeks),
        Mar = x.Where(y => y.Month == "March").Sum(y => y.Weeks),
        Dec = x.Where(y => y.Month == "December").Sum(y => y.Weeks),
        //Add more month here
        Total = x.Sum(y => y.Weeks)
    });

这是fiddle