0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67

1 Answers1

3

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());
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 2
    Hey! Wow! You just saved my life! Thank you so much. And for the use of `Dictionary`. Think you can explain what you did? For others to read in the future :) – Boy Pasmo Oct 24 '14 at 16:52
  • @BoyPasmo, It is using [Enumerable.ToDictionary](http://msdn.microsoft.com/en-us/library/vstudio/bb549277(v=vs.100).aspx) , I added a link, but I think It is simple to understand. – Habib Oct 24 '14 at 16:54