Home > other >  Group data into a type and list of object members
Group data into a type and list of object members

Time:03-15

Take the following example code:

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"}]
     }
]
*/

I've tried multiple variations with GroupBy but didn't have any success achieving the desired format:

var productGroups = queryResults.GroupBy(x => x.size).ToList(); returns a List<IGrouping<int, Product>> which isn't quite what I want.

CodePudding user response:

You could just group by Size and assign Products to the list of items in the group. The following returns an anonymous object:

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

If you need a concrete class/record ProductGroup then the query is very similar to the above:

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

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

But it also looks like your datatype matches Dictionary<int, List<Product>>. So you could use ToDictionary after grouping:

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