首页 > 解决方案 > 使用 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>");
    }
}

标签: c#linqgroup-by

解决方案


这是一个包含示例数据的解决方案,您可以自己测试:

        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 ggroup p by c into g.


推荐阅读