LINQ - 有没有办法在不使用 ForEach 的情况下在分组后获取元素值?
我有一个包含 CategoryId 字段的 Items 表。这是类别表中的外键。我想按 CategoryId 对项目进行分组并返回 Items 和 Category.Name。
我知道我可以在 C# 中执行此操作:
var ItemsByCat =
from i in Items
group i by i.CategoryId into g
select g
foreach(var n in ItemsByCat)
{
blah, blah
}
我的问题是 - 有没有一种方法可以获取分组的元素值部分,而无需使用循环进行迭代?比如:
from i in Items
group i by i.CategoryId into g
select new {
CategoryID = g.Key,
CategoryName = ???,
Items = ???
}
非常感谢,
BK
I have an Items table that contains a CategoryId field. This is an FK into a Categories table. I want to group my Items by CategoryId and return the Items and Categories.Name.
I know I can do this in C#:
var ItemsByCat =
from i in Items
group i by i.CategoryId into g
select g
foreach(var n in ItemsByCat)
{
blah, blah
}
My question is - is there a way to get at the element values part of the grouping without having to iterate through with a loop? Something like:
from i in Items
group i by i.CategoryId into g
select new {
CategoryID = g.Key,
CategoryName = ???,
Items = ???
}
Many thanks,
BK
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为这就是您正在寻找的:
编辑:我希望这能从评论中回答您的问题。
g
是按CategoryId
分组的项目集合。select
中的Items
可以是包含您需要的Item
属性的任何子集的投影。例子:I think this is what you're looking for:
EDIT: I hope this answers your question from the comments.
g
is a collection of Items grouped by theirCategoryId
.Items
in theselect
can be a projection including whatever subset ofItem
properties you require. Example:加入类别表怎么样?
What about joining the Categories table?
CategoryName
应为i.Category.CategoryName //name 属性
如果您已正确设置关系,则
。这些项目应该是分组依据的值,不确定为什么您需要再次执行此操作。
CategoryName
should bei.Category.CategoryName //the name property
given you have the relationship setup properly.
The items should be the values of group by, not sure why you'd need to do it again.
假设您在变量类别中有一个类别集合,它看起来像这样:
Assuming you have a collection of Categories in a variable categories it would look like this: