如何在linq查询中使用分组依据? [英] how to use group by in a linq query?

查看:53
本文介绍了如何在linq查询中使用分组依据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品列表,其中包含产品名称,productprice和类别.我想编写一个 linq 查询来根据类别对所有产品进行分组.我尝试了以下方法:

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

这篇关于如何在linq查询中使用分组依据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆