本文介绍了如何在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.
推荐答案
您需要从组中选择产品:
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查询中使用分组依据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!