如何获得linq中的计数? [英] How can I get the count in linq?

查看:52
本文介绍了如何获得linq中的计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 products 的表,该表的列为:

I have table called products with columns:

productid ,
productname,
productprice
categoryid

我的问题是我想根据产品名称以及详细信息获取产品数量.我想在 DataGridView 中显示数据.我如何知道单个产品名称的产品数量,如下所示?

My problem is I want to get the number of products depending on product name along with details. I want to show the data in DataGridView. How can I know the number of products for a single product name like below?

productid        productname          productavailable        productprice
--------------------------------------------------------------------------
1                product A            2 products(product A)   100
2                product B            5 Products(product B)   200

就像上面的表格一样,我必须在 DataGridView 中显示.我正在使用LINQ和C#,我的 DbContext 名称是 tsgdbcontext .

Like the above table I have to display in DataGridView. I am using LINQ and C# and my DbContext name is tsgdbcontext.

推荐答案

GroupBy 与包含分组属性的键一起使用.然后选择键属性以及分组中每个键的计数.

Use GroupBy with a key that contains your grouping properties. Then select out the key properties along with the count of each from the grouping.

var query = tsgdbcontext.Products
                        .GroupBy(p => new {
                            p.ProductId,
                            p.ProductName,
                            p.ProductPrice
                         })
                        .Select(g => new {
                            g.Key.ProductId,
                            g.Key.ProductName,
                            g.Key.ProductPrice,
                            Available = g.Count()
                        });

这篇关于如何获得linq中的计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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