我的表名为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
。
答案 0 :(得分:41)
将GroupBy
与包含分组属性的密钥一起使用。然后select
输出关键属性以及分组中每个属性的计数。
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()
});
答案 1 :(得分:31)
不确定我是否完全理解+做出一些假设,但这里是一个示例linq查询,根据一些任意选择标准(id = 2且价格大于100)产生计数...
int count = (from p in tsgdbcontext.Products
where p.productid == 2 && p.productprice > 100
select p).Count();