将数据分组为对象成员的类型和列表

Group data into a type and list of object members

以下面的示例代码为例:

public record ProductGroups(int size, List<Product> products);
public record Product(int size, int Id, string style);

queryResults = new List<Product>()
{
     new Product(1, 1, "short sleeve"),
     new Product(1, 2, "long sleeve"),
     new Product(1, 3, "hoodie"),
     new Product(2, 4, "med short sleeve"),
     new Product(2, 5, "med long sleeve")
}

/* Want to turn queryResults into a list<ProductGroups> object that looks like this:
[
     {
          size: 1,
          products: [{1, 1, "short sleeve"}, {1, 2, "long sleeve"} {1, 3, "hoodie}]
     },
     {
          size: 2,
          products: [{2, 4, "med short sleeve"}, {2, 5, "med long sleeve"}]
     }
]
*/

我尝试了 GroupBy 的多种变体,但没有成功达到所需的格式:

var productGroups = queryResults.GroupBy(x => x.size).ToList(); returns List<IGrouping<int, Product>> 这不是我想要的。

您可以按 Size 分组并将 Products 分配给组中的项目列表。以下returns一个匿名对象:

var result = queryResults.GroupBy(r => r.size)
                         .Select(g => new { Size = g.Key, Products = g.ToList() });

如果您需要具体的 class/record ProductGroup 那么查询与上面的非常相似:

var result = queryResults.GroupBy(r => r.size)
                         .Select(g => new ProductGroup(g.Key, g.ToList()));

public record ProductGroup(int Size, List<Product> Products);

但看起来您的数据类型也匹配 Dictionary<int, List<Product>>。所以你可以在分组后使用 ToDictionary:

var result = queryResults.GroupBy(r => r.size)
                         .ToDictionary(r => r.Key, r => r.ToList());