C#How to GroupBy如何将一个项目放入多个组中 [英] C# How to GroupBy so that an item can be put into multiple groups
问题描述
我有一堆文章,我想按类别整理。这对于GroupBy(x => x.Category)来说很简单,除了一些文章有多个类别。如何分组我的文章,以便如果他们有两个类别,它们将被放到两个类别分组中?
例如:
第1条,类别:苹果,橙子
第2条,类别:苹果
第3条,cateogry:橙子
$ c $我最终会得到两个类别,苹果和橙子:
苹果:第1条第2款
橙色:第1条第3款
解决方案如果我已正确理解您的问题,则可以执行以下操作:
var groups =
products.SelectMany(p => p.Categories,
(p,c)=> new {Product = p,Category = c})
.GroupBy (p => p.Category,p => p.Product);
相关的 SelectMany
过载是 this one 。
等价查询语法更好:
var groups = from p in products
从c。p.Categories
group p by c into g
select g;
感谢 Servy 指出了将流利版翻译为查询语法的显而易见的方法(我试图将其转换为字面意思)。
I have a bunch of articles and I want to organize them by category. This would be simple with a GroupBy(x => x.Category), except that some articles have multiple categories. How can I group my articles so that if they have two categories, they are put into both category groupings?
example:
Article 1, category:apples, oranges
Article 2, category:apples
Article 3, cateogry:oranges
I would end up with two categories, apples and oranges:
apples: Article 1, Article 2
orange: Article 1, Article 3
解决方案 If I've understood your problem correctly, you can do the following:
var groups =
products.SelectMany(p => p.Categories,
(p, c) => new { Product = p, Category = c })
.GroupBy(p => p.Category, p => p.Product);
The relevant SelectMany
overload is this one.
The equivalent query syntax is much nicer:
var groups = from p in products
from c in p.Categories
group p by c into g
select g;
Thanks to Servy for pointing out the obvious way to translate the fluent version to the query syntax one (I was trying to convert it way too literally).
这篇关于C#How to GroupBy如何将一个项目放入多个组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!