lambda 表达式中的 GroupBy
from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
你会如何将上面的内容写成 lambda 表达式?我陷入了 group into
部分。
from x in myCollection
group x by x.Id into y
select new {
Id = y.Key,
Quantity = y.Sum(x => x.Quantity)
};
How would you write the above as a lambda expression? I'm stuck on the group into
part.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
查询延续(select...into 和group...into,但不是 join...into)相当于仅拆分查询表达式。因此,我喜欢将您的示例视为:
将它们更改为点表示法:
然后您可以将它们组合回来:
一旦您弄清楚 C# 编译器对查询表达式的作用,其余的就相对简单了:)
Query continuations (select...into and group...into, but not join...into) are equivalent to just splitting up the query expression. So I like to think of your example as:
Change those into dot notation:
Then you could combine them back:
Once you work out what the C# compiler does with query expressions, the rest is relatively straightforward :)
因此,对于这里的大多数答案,每个人似乎都在处理从组的计数中获取一个简单的 Id 对象,以及 Key 本身,即 group.Key。
虽然这可能是它的主要用途。并没有真正满足我的需求。
对于我自己的情况,我基本上想按某些对象属性进行分组,然后从该组中获取特定对象。这是示例代码。
如果你更愿意使用 foreach 循环(我更喜欢 lambda,因为我发现它更容易阅读),但如果你这样做,你可以这样做。
希望这对某人有帮助。 :)
So, for most of the answers here, everyone seems to be dealing with getting a simple object of Id made from count of the group, and the Key itself which is group.Key.
Although thats probably the main useage of this. Didn't really satisfy my needs.
For my own case, I basically wanted to group by some object property, then fetch a specific object from that group. Here's a sample code.
If you would rather use a foreach loop (I prefer lambda as I find it easier to read), but if you do, you could do it like so.
Hope this helps someone. :)