Linq to group by 2 columns in C# [duplicate]

2019-05-19 06:22发布

问题:

This question already has an answer here:

  • Group By Multiple Columns 13 answers

I have a simple Linq query, which groups by one field Team:

var qbt = db.Calls.GroupBy(x => x.team).Select(call => new
        {
            Team = call.Key,
            Number=call.Count()
        });

Which returns:

Team  Number
ta    100 
tb    98 
tc    123

How do I change the query to have an additional column "status", so that it returns:

Team  Number Status
ta    40     Open
ta    60     Closed
tb    58     Open
tb    40     Closed
tc    1      Open
tc    122    Closed

I tried adding another group:

var qbt = db.Calls.GroupBy(x => x.team).GroupBy(y => y.status).Select(call => new
        {
            Team = call.Key,
            Status = call.Key2,
            Number=call.Count()
        });

... but that won't compile.

Thank you, Mark

回答1:

You need to create new anonymous type inside groupping, that should do the trick.

var qbt = db.Calls
    .GroupBy(x => new { Team = x.team, Status = x.status })
    .Select(call => new
    {
        Team = call.Key.Team,
        Status = call.Key.Status,
        Number=call.Count()
    });


回答2:

You can group on an anonymous type:

.GroupBy(x => new { x.team, x.status })

With the corresponding select:

.Select(call => new
    {
        Team = call.Key.team,
        Status = call.Key.status,
        Number = call.Count()
    });