Boy Pasmo
Boy Pasmo

Reputation: 8471

How to group data and store them in a new list by group

How can you store the data in the list by group?

Say,

public class ProductPrice
{
  public string Name { get; set }
  public decimal Price { get; set; }
  // Date and other properties
}

then having a record like this:

+--------+--------+
| Name   | Price  |
+--------+--------+
| Chair  | 11     |
| Table  | 15     |
| Table  | 30     |
| Window | 24     |
| Chair  | 29     |
+--------+--------+

What should be done in order to achieve a list something like this:

{
  {
    new ProductPrice { Name = "Chair", Price = 11 },
    new ProductPrice { Name = "Chair", Price = 29 },
  },
  {
    new ProductPrice { Name = "Table", Price = 15 },
    new ProductPrice { Name = "Table", Price = 30 }
  },
  {
    new ProductPrice { Name = "Window", Price = 24 }
  }
}

As you can see, they are grouped by their Name and store them in a list per group. It would be great to feed them to a, say, line chart to see their price trends. It's just that I am having hard time creating the list.

In a nutshell, can I create a List that is grouped by Products Name? Also, products can have new record as well?

Upvotes: 0

Views: 532

Answers (1)

Habib
Habib

Reputation: 223187

What you need is a List<List<ProductPrice>>, you can do:

List<List<ProductPrice>> groupedList = list.GroupBy(r => r.Name)
                    .Select(grp => new
                            {
                                List = grp.Select(r => r).ToList()
                            })
                    .Select(r => r.List)
                    .ToList();

This will return you three values in your List one for each group.

You can also project your results to Dictionary<string, List<ProductPrice>>, where your key would be the name of Product and value will contain List<ProductPrice> related to Key. Use Enumerable.ToDictionary like:

Dictionary<string, List<ProductPrice>> groupedList = list.GroupBy(r => r.Name)
                        .ToDictionary(grp => grp.Key, grp => grp.ToList());

Upvotes: 3

Related Questions