c# - 我怎样才能得到linq中的计数?

标签 c# linq entity-framework linq-to-entities

我有一个名为 products 的表,其中包含以下列:

productid ,
productname,
productprice
categoryid

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

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

最佳答案

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

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

关于c# - 我怎样才能得到linq中的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7372805/

相关文章:

c# - 如何使用 Linq 表达式树从 Span<T> 中获取值?

在用 OR 连接的 where 子句中使用动态谓词的 linq 查询

c# - 具有多个表的 Linq

entity-framework - 什么会导致 Entity Framework 在现有数据上保存已卸载(但可延迟加载)的引用?

c# - 无法与装饰层上的项目交互

c# - 为什么 add-migration 命令没有创建迁移?不识别包裹

c# - 使用 linq 或 xpath 获取 xml 中的所有文本节点

c# - 无法从用法推断 GroupJoin 方法的类型参数

c# - 如何通过将所有元素加或在一起来简化列表?

c# - Add-Migration 一个列名被多次列出