views:

17

answers:

2

Hello

I have an mvc-page that lists categories, and I would like to have it to count the number of products per category. It's IQueryable.

<% foreach (var item in Model.Categories) { %>
.....
<td><%: item.CategoryName %></td>
<td><%: item.Products.Count() %></td>

It lists: 5 5

Instead of: 3 2

Any Ideas how I can "partition" it per category?

/M

+1  A: 

Group by category name and get sum of all the product counts per category. See if this works for you.

var query = Model.Categories
                 .GroupBy(item => item.CategoryName)
                 .Select(g => new {
                             CategoryName = g.Key,
                             Count = g.Sum(item => item.Products.Count())
                         });
Jeff M
A: 

it is also possible with the LINQ syntax:

var query = from item in Model.Categories
            group item by item.CategoryName into g
            select new { CategoryName = g.Key, Count = g.Count() };
Wouter Janssens - Xelos bvba