简体   繁体   English

如何在linq查询中使用group by?

[英]how to use group by in a linq query?

I have a list of products with productname, productprice & category. 我有一个包含productname,productprice和category的产品列表。 I want to write a linq query to group all the products according to category. 我想写一个linq查询来根据类别对所有产品进行分组。 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. OK ..需要更多帮助,现在当我运行代码时,它只是显示一个表格,其中类别列显示了预期的两个类别,但产品列没有显示任何数据。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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