c# - 使用 GroupBy 从 List 中创建 SubLists,其中 GroupBy 值为 List
问题描述
我有一个要显示的简单列表,按它所属的类别分组。我见过的所有示例都使用 GroupBy 但只有一个 ID,我无法弄清楚如何使用 List 来执行此操作。如果产品出现在两个类别下,则可以。
public class Product
{
public int Id { get; set; }
public string Title { get; set; }
public List<Category> Categories { get; set; }
}
StringBuilder ProductList = new StringBuilder();
var p = _products.GroupBy(a => a.Categories);
foreach (var item in p)
{
ProductList.Append($"<p><strong>{item.Key}</strong><br/>");
foreach (var e in item)
{
ProductList.Append($"{e.Title}");
ProductList.Append("</p>");
}
}
解决方案
这是一个包含示例数据的解决方案,您可以自己测试:
var categories = Enumerable.Range(0, 10).Select(n => new Category { Id = n }).ToArray();
var products = new[]
{
new Product { Id = 1, Title = "P1", Categories = new List<Category> { categories[0], categories[1], categories[2] } },
new Product { Id = 2, Title = "P2", Categories = new List<Category> { categories[0], categories[1], categories[3] } },
new Product { Id = 3, Title = "P3", Categories = new List<Category> { categories[0], categories[2], categories[3] } },
new Product { Id = 4, Title = "P4", Categories = new List<Category> { categories[0], categories[2], categories[3] } },
new Product { Id = 5, Title = "P5", Categories = new List<Category> { categories[0], categories[3], categories[5] } },
new Product { Id = 6, Title = "P6", Categories = new List<Category> { categories[0], categories[4], categories[5] } },
};
var categoryGroups =
from p in products
from c in p.Categories
group p by c.Id into g
select g;
foreach (var categoryGroup in categoryGroups)
{
Console.WriteLine($"Category {categoryGroup.Key}:");
foreach (var product in categoryGroup)
{
Console.WriteLine($"\tProduct {product.Id}: {product.Title}");
}
Console.WriteLine("-----------------------------------------------------");
}
我假设类Category
有一些 id 属性,例如Id
,分组依据。如果它是基于参考的分组,您可以替换group p by c.Id into g
为group p by c into g
.
推荐阅读
- environment-variables - Wallaby.js 不工作(无法从 'node_modules/cpm-config.app.js' 中找到模块 '../../config-test.json')
- angular - 量角器角度同步失败,来自 webdriver 的错误 - “无法读取未定义的属性 '$injector'”
- flutter - 如果用户注销并重新登录,WillPopScope 将不起作用
- azure-virtual-machine - 如何使用 Azure VPN 作为代理网关
- linux - 无法使用正确的密码连接到 ssh
- ios - 加载太多图像时,Ionic 5 iOS 应用程序重新启动
- java - @Transactional 注释仅在类中声明时有效
- python - 如何在python中显示更好的输出解释
- c# - UWP SQLite 错误:“尝试写入只读数据库”
- c# - Azure 不显示托管 .net 核心 API 的自定义错误消息