using group by in linq in controller

Total Post:52

 678  View(s)
Rate this:

currently i have following linq

  ViewBag.Products = db.Transaction.GroupBy(n => n.ProductName,
              (key, values) => new { ProductName = key, Count = values.Count() });

in view i need to get  the list of each product and its count

but in view i get the query printed

if i use productid i get productid      count

i want to group by productid but name and count shld be displayed


product1       20

product2        18

product3         4

  1. Post:45

    Re: using group by in linq in controller

    Hi manish

    According to your description I have used the following Linq statement and it works well.

      var products = from p in db.Transactions                            
                                group p
                                by p.productid                          
                                into g
                                select g

    viewbag will convert anonymous type to object type,so I convert it to Json type and it will be better  to show in the view 

       ViewBag.productTest = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(products));

    Your view code is

            @foreach (var item  in ViewBag.products)
                    @foreach (var t in item) {

    Hope it helps you

      Modified On Apr-11-2018 10:49:41 PM