user2915962
user2915962

Reputation: 2711

Count occurrences of item in list

Have a look at this code:

 @foreach (var item in Model.Categories)
        {
          <li><a href="#">@item</a></li>
        }

Model.Categories is a list of strings containing categories for a blog. The list contains several occurrences of the same category and I would like to display the result like this:

Music(5)

Where 5 is the number of blogposts under the category Music. Any tips on how to go about doing this?

Upvotes: 3

Views: 105

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

A little bit of Linq will help. Try using the GroupBy method, like this:

@foreach (var group in Model.Categories.GroupBy(c => c))
{
    <li><a href="#">@group.Key (@group.Count())</a></li>
}

Of course, you can do this in the controller action, too (I'm guessing the variable names):

...
viewModel.PostCounts = 
    (from p in db.Posts
     group p by p.Category into g
     select new PostCountViewModel
     {
         CategoryName = g.Key,
         PostCount = g.Count()
     })
    .ToList();

return View(viewModel);

And then in your view:

@foreach (var item in Model.PostCounts)
{
    <li><a href="#">@item.CategoryName (@item.PostCount)</a></li>
}

I'd generally recommend going with this second option if you can pull back all the post counts from the database in a single query, rather than having to loop through the collections in memory. I'm sure you'll have to make adjustments, but hopefully you get the general idea of how this would look.

Upvotes: 2

Related Questions