how to use group by in a linq query?

Badhon Jain picture Badhon Jain · Jun 17, 2012 · Viewed 15.7k times · Source

I have a list of products with productname, productprice & category. I want to write a linq query to group all the products according to category. I have tried the following:

var p = from s in productlist
        group s by s.Category into g
        select new { Category = g.Key, Products = g};

With this query, it's showing a table with two column as category & product. Category column has two categories as expected but under products column, there is no data. I would love to have all the product list separated by the category.

Answer

Tim Schmelter picture Tim Schmelter · Jun 17, 2012

OK..Need a bit more help on this, now when I run the code, its just showing a table with categories column showing two categories as expected, but the product column not showing any data.

You need to select the products from the group:

Products = g.Select(p => p).ToList()

Have a look at following with some additional properties.

var categories = from s in productlist
                group s by s.category into g
                select new { 
                    Category = g.Key, 
                    Products = g.ToList(),
                    ProductCount = g.Count(),
                    AveragePrice = g.Average(p => p.productprice)
                };