---
title: "using group by in linq in controller"  
description: "using group by in linq in controller"  
author: "Manish Kumar"  
published: 2017-05-25  
updated: 2017-05-28  
canonical: https://www.mindstick.com/forum/34301/using-group-by-in-linq-in-controller  
category: "c#"  
tags: ["mvc4"]  
reading_time: 1 minute  

---

# using group by in linq in controller

currently i have following [linq](https://www.mindstick.com/articles/12007/language-integrated-query-linq-queries)

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

\
in [view](https://yourviews.mindstick.com/view/84701/layoffs-in-google-india-2023-view) i need to get the list of each [product](https://www.mindstick.com/articles/75385/full-product-keys) and its [count](https://www.mindstick.com/forum/157774/selecting-count-with-distinct)

but in view i get the [query](https://www.mindstick.com/blog/202/sub-query-in-sqlserver) printed

if i use productid i get productid count

i want to [group](https://yourviews.mindstick.com/view/81323/adani-green-energy-group-bags-world-s-biggest-solar-bid) by productid but [name](https://yourviews.mindstick.com/view/87450/how-to-generate-a-brand-name-using-linkedin-comprehensive-guide) and count shld be displayed

[requirement](https://yourviews.mindstick.com/view/85169/becoming-an-influencer-requirement-of-skills-and-knowledge)

product1 20

product2 18

product3 4

## Replies

### Reply by Sunil Singh

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


---

Original Source: https://www.mindstick.com/forum/34301/using-group-by-in-linq-in-controller

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
