C# How to GroupBy so that an item can be put into multiple groups

孤人 提交于 2020-01-06 06:51:09

问题


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

回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/49499885/c-sharp-how-to-groupby-so-that-an-item-can-be-put-into-multiple-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!