Linq在C#中按2列分组 [英] Linq to group by 2 columns in C#
本文介绍了Linq在C#中按2列分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的Linq查询,该查询按一个字段Team
进行分组:
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()
});
哪个返回:
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
我尝试添加另一个组:
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.
谢谢你,马克
推荐答案
您需要在分组内创建新的匿名类型,这可以解决问题.
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()
});
这篇关于Linq在C#中按2列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文