开发者

How to get sum in nested collection via LINQ

class YearlyData
{
    Month开发者_StackOverflow社区lyData[] monthlyData = new MonthlyData[12];
}

class MonthlyData
{
    int Salary;
}

Given I have a List<YearlyData>, how can I find total salary for a given month for the number of years. Example for three years I need total salary given for 1st month & subsequent months.


If you want the sum of all the Salaries for April:

List<YearlyData> l;
l.Sum(yd => yd.monthlyData[3].Salary);

If I misread your question, and you really want all the salaries for April & subsequent months (in the year)

l.Sum(yd => yd.monthlyData.Skip(3).Sum());


Something like this:

list.SelectMany(x => x.monthlyData
                      .Select((m, i) => new {month = i+1, 
                                             data = m.Salary}
               ))
    .GroupBy(x => x.month)
    .Select(x => new {month = x.Key,
                      total = x.Sum(m => m.data)});

This will give you a list with twelve entries, one for each month along with the total amount of that month.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜