简体   繁体   English

C#如何分组,以便可以将一个项目分为多个组

[英]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.

相关问题 C#linq groupby返回错误的组 - C# linq groupby returns incorrect groups 如何在图片框后面放置标签,以便在图片框c#下可以看到标签? - How to put label behind the picturebox so label can be seen under picturebox c#? 可以在 C# 中使用 SQL AND 语句引用多个 C# 变量吗? 如果是这样,如何? - Can one use an SQL AND-statement in C# referencing multiple C# variables? If so, how? C#绑定:如何在BindingList中禁用CurrencyManager,以便不维护当前项位置并且不发信号? - C# Binding: How can I disable the CurrencyManager in BindingList so Current Item position is not maintained and not signaled? 如何将列表项拖放到标签上,使其成为C#中标签的文本? - How can you drag and drop a list item to a label so it's the label's text in C#? 如何链接我的C#脚本,以便项目数影响Unity游戏中的得分? - How can I link my C# scripts so that item count influences score in my Unity game? 具有多个组级别的 GroupBy - GroupBy with multiple groups level GroupBy具有多个组作为层次结构 - GroupBy with multiple groups as a hierarchy 无法在MongoDB C#驱动程序中进行多个组 - Can't do multiple groups in MongoDB C# Driver 如何使用数组值对多个数组进行C#linq GroupBy - How to C# linq GroupBy multiple arrays with array values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM