C# LINQ group by 表达式语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1796165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:54:42 来源:igfitidea点击:
LINQ group by expression syntax
提问by agnieszka
I've got a T-SQL query similar to this:
我有一个与此类似的 T-SQL 查询:
SELECT r_id, r_name, count(*)
FROM RoomBindings
GROUP BY r_id, r_name
I would like to do the same using LINQ. So far I got here:
我想使用 LINQ 做同样的事情。到目前为止,我到了这里:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by roomBinding.R_ID into g
select new { ID = g.Key };
How can I extract the count(*) and r_name part?
如何提取 count(*) 和 r_name 部分?
采纳答案by bruno conde
Try this:
尝试这个:
var rooms = from roomBinding in DALManager.Context.RoomBindings
group roomBinding by new
{
Id = roomBinding.R_ID,
Name = roomBinding.r_name
}
into g
select new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
};
Edit by Nick - Added method chain syntax for comparison
由 Nick 编辑 - 添加了用于比较的方法链语法
var rooms = roomBinding.GroupBy(g => new { Id = g.R_ID, Name = g.r_name })
.Select(g => new
{
Id = g.Key.Id,
Name = g.Key.Name,
Count = g.Count()
});