using group by in linq in controller

Total Post:52

Points:366
Mvc4 
C#
 598  View(s)
Ratings:
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

requirement  

product1       20

product2        18

product3         4

  1. Post:45

    Points:323
    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

    <table>
            @foreach (var item  in ViewBag.products)
            {
                <tr>
                 <td>
                     @item[0].productid
                 </td>
                    <td>
                        @item.Count;
                    </td>
                    @foreach (var t in item) {
                    <td>
                        @t.ProductName;
                    </td>
                                                  
                    }
                </tr>            
            }
     
        </table>


    Hope it helps you

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

Answer