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

2019-08-18 12:18发布

问题:

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.