sandman
sandman

Reputation: 3

How to get sum in nested collection via LINQ

class YearlyData
{
    MonthlyData[] 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.

Upvotes: 0

Views: 1286

Answers (2)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

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.

Upvotes: 0

Scott Weinstein
Scott Weinstein

Reputation: 19117

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());

Upvotes: 2

Related Questions