[英]C# How to GroupBy so that an item can be put into multiple groups
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.
使用GroupBy(x => x.Category),这很简单,除了某些文章具有多个类别。 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 . 相关的
SelectMany
重载就是这一点 。
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). 感谢Servy指出了将流利的版本转换为查询语法的一种明显方法(我试图从字面上转换它)。
var categories = articles.selectMany(x => x.categoies).Distinct().Select(x => {
var categoriziedArticles = articles.Where(z => z.cagories.Conains(x)));
return new Category(categoriziedArticles);
});
Maybe something like this. 也许是这样的。 I have not tried compiling this.
我没有尝试编译这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.