Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the count in linq?

I have table called products with columns:

productid ,
productname,
productprice
categoryid

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

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

like image 277
Glory Raj Avatar asked Sep 10 '11 15:09

Glory Raj


2 Answers

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()
                        });
like image 96
tvanfosson Avatar answered Oct 14 '22 22:10

tvanfosson


Not sure I am understanding exactly + making some assumptions but here is an example linq query that produces a count based on some arbitrary selection criteria (id=2 and price greater than 100)...

int count = (from p in tsgdbcontext.Products
             where p.productid == 2 && p.productprice > 100
             select p).Count();
like image 39
blins Avatar answered Oct 15 '22 00:10

blins