我注意到这两个LINQ查询产生相同的输出。请问在分组方面,这两个查询有什么不同吗?是因为 into
可以按照2个元素进行分组吗?
var groupBy = from n in numbers
group n by n;
同时:
var groupBy = from n in numbers
group n by n into g
select g;
https://codeblog.jonskeet.uk/2010/09/15/query-expression-syntax-continuations/
当在“group x by y”或“select x”子句之后使用“into”时,它被称为查询延续。 (请注意,“join ... into”子句不是查询延续;它们非常不同。)查询延续实际上表示:“我已完成一个查询,并且我想使用结果进行另一个查询...但全部在一个表达式中。”关键字“into”使您的查询延续,它实际上在新的范围变量中使用旧查询的结果开始了一个新的查询。方法语法中立即显现出差异:
Original Answer翻译成:“最初的回答”
var groupBy = numbers.GroupBy(n => n);
vs. (with into
)
var groupBy = numbers.GroupBy(n => n).Select(g => g);
var group = from c in Company
group c by c.City;
into
和 select
,我们就需要这些内容。"最初的回答"var group = from c in Company
group c by c.City
into cg
select new
{
City = cg.Key,
NumberOfCompanies = cg.Count()
};
In method syntax:
var group = Companies
.GroupBy(c => c.City)
.Select(gc => new
{
City = cg.Key,
NumberOfCompanies = cg.Count()
});
Key
和 Count
。
foreach (var item in groupBy)
{
Console.WriteLine(item.Key + "-" + item.Count());
} - SteveSelect
没有添加任何新内容,Select(g => g)
是多余的。只有在一个查询中想要对结果进行特殊处理时,才需要添加Select
调用(或into-select
)。 - Gert Arnold
into
关键字在较长的 LINQ 查询中通常用于为查询结果命名,并且还支持聚合函数如max
、sum
等。” - Freggar