簡體   English   中英

如何在 linq 中獲得計數?

[英]How can I get the count in 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM