[英]Linq: how to group by many-to-many relationship?
I have an entity Item like next: 我有一个像下一个实体项目:
class Item
{
int Id;
string Name;
int GroupId;
virtual Group Group; //refers to Group table
string Size;
virtual ICollection<Set> Sets; //refers to many-to-many relation
}
So I want to group all items like next: 所以我想将下一个项目分组:
ICollection<IGrouping<string, Item>> list = AllItems.GroupBy(x => x.Group.Name).ToList();
ICollection<IGrouping<string, Item>> list = AllItems.GroupBy(x => x.Size).ToList();
And I want the same, but with Sets. 而且我想要相同,但使用套装。 Is it possible somehow?
有可能吗?
To clarify. 澄清。 For example, Item1 contains in every set, then I want in the end of grouping by Sets next list:
例如,Item1包含在每个集合中,然后我想在分组结束时按下一个列表:
Set 1
Item 1
Item 2
Set 2
Item 1
Item 3
Set 3
Item 1
Item 4
.....
Note, I need same structure ICollection<IGrouping<string, Item>>
, to pass it next in code. 注意,我需要相同的结构
ICollection<IGrouping<string, Item>>
,然后在代码中传递它。 I was thinking maybe to create intermediate structure, which can accept both ICollection<IGrouping<string, Item>>
and Sets list containing my items? 我想也许可以创建中间结构,它可以接受
ICollection<IGrouping<string, Item>>
和包含我的项目的集合列表?
SelectMany
+ GroupBy
with a value selector: SelectMany
+ GroupBy
带有值选择器:
ICollection<IGrouping<string, Item>> list = AllItems
.SelectMany(x => x.Sets
.Select(y => new
{
Key = y,
Value = x
}))
.GroupBy(x => x.Key.Name, x => x.Value)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.