简体   繁体   中英

how to use group by in a linq query?

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.

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)
                };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM