fearofawhackplanet
fearofawhackplanet

Reputation: 53378

Linq GroupBy and multiple columns

class ExpenseClaim
{
    int EmployeeId;
    int Team;
    double Cost;
}


List<EmployeeExpense> GetEmployeeExpenses()
{
    return _expenseClaims // `_expenseClaims` is `List<ExpenseClaim>`
             .GroupBy(e => e.EmployeeId)
             .Select(x =>
                new EmployeeExpense(
                        x.Key,
                        // TODO: employee team?
                        x.Sum(e => e.Cost)
                );
}

Excuse the rather contrived example.

How do I get the employee team in GetEmployeeExpenses? I'm assuming I need a second group by but I can't work out the syntax.

Note that for a given employee, their Team will always be the same anyway, so I'd be happy to take the Team of for example the first grouped by record.

so...

ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 100 }
ExpenseClaim { EmployeeId = 1, Team = Sales, Cost = 50 }

=>

EmployeeExpense { EmployeeId = 1, Team = Sales, Cost = 150 }

Upvotes: 3

Views: 6173

Answers (2)

Alex Bagnolini
Alex Bagnolini

Reputation: 22382

Query expression version of it (might be easier to read, depending on situation and amount of grouping):

IEnumerable<EmployeeExpense> GetEmployeeExpenses(List<ExpenseClaim> claims)
{
    return 
        from c in claims
        group c by c.EmployeeId into groupedById
        from g in groupedById
        group g by g.Team into groupedByTeam
        let firstElement = groupedByTeam.First()
        select new EmployeeExpense {
            EmployeeId = firstElement.EmployeeId,
            Team = firstElement.Team,
            Cost = groupedByTeam.Sum(e => e.Cost)
        };
}

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126794

In your particular case, you could use x.First().Team inside your Select to get your team information.

For other cases of actually needing to group on multiple fields, you could group on an anonymous type. Such as

someQuery.GroupBy(f => new { f.Foo, f.Bar }).Select(...);

Upvotes: 9

Related Questions