怎么才能得到linq的计数
我有一个名为带列的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
与包含分组属性的键一起使用。 然后从分组中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() });
不确定我是否完全理解+做出一些假设,但这里是一个示例linq查询,它根据一些任意选择标准(id = 2且价格大于100)产生计数…
int count = (from p in tsgdbcontext.Products where p.productid == 2 && p.productprice > 100 select p).Count();