开发者

LINQ - Is there a way to get element values after grouping without ForEach?

开发者 https://www.devze.com 2023-04-11 07:21 出处:网络
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 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 i开发者_JAVA百科nto 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


I think this is what you're looking for:

from i in Items
group i by i.CategoryId into g
select new 
{
    CategoryID = g.Key,
    CategoryName = g.First().Category.Name,
    Items = g
}

EDIT: I hope this answers your question from the comments.

g is a collection of Items grouped by their CategoryId. Items in the select can be a projection including whatever subset of Item properties you require. Example:

from i in Items
group i by i.CategoryId into g
select new 
{
    CategoryID = g.Key,
    CategoryName = g.First().Category.Name,
    Items = g.Select(a => new{a.ItemID, a.ItemName})
}


What about joining the Categories table?

from i in Items
join c in Categories on i.CategoryId equals c.Id
group i by i.CategoryId into g
select new {
    CategoryID = g.Key,
    CategoryName = c.Name,
    Items = i
}


CategoryName should be i.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:

var ItemsByCategory = 
  from i in items
  join c in categories on i.CategoryId equals c.Id
  group i by i.CategoryId into g
  select new {
    CategoryId=g.Key,
    CategoryName=c.Name,
    Items=g.Items
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号