0

I want to display list of items which belong to certain category like this:

Category I

  • Item 1
  • Item 2
  • Item 3

Category II

  • Item 6
  • Item 7

Category III

  • Item 10
  • Item 11
  • Item 12
  • Item 13

What is the best (and easiest) way to do this? I started doing this with two queries - one gets all goals, and then in foreach loop (in controller) I call another query which gets all items from this category, but then things got complicated... I have no idea in what type of object to store these items and how to pass all this together to a view.

Any idea?

Thanks!

ilija veselica
  • 9,414
  • 39
  • 93
  • 147

1 Answers1

1

to select:

var query = from item in itemstable
group item by item.category into y
select new { key = y.Key, grouping = y };

then to access:

foreach(var g in query)
{
    //this is each grouping
    foreach(var item in query.grouping)
    {
        //this is each item in each group
    }
}
David Fox
  • 10,603
  • 9
  • 50
  • 80
  • What is return type in this query? This looks pretty simple :) – ilija veselica Jun 14 '10 at 12:09
  • are you asking for the type of `query`? I think it's IEnumerable – David Fox Jun 14 '10 at 12:20
  • Yes, it works in LinqPAD, but I have no idea how to handle this in controller? Is there any tutorial about IGrouping? – ilija veselica Jun 14 '10 at 12:31
  • What am I suppose to inherit now in View? – ilija veselica Jun 14 '10 at 12:35
  • does this post help you? you probably don't want to group this in the controller because you would have to pass ViewData and the IEnumerable to the view. Just do this grouping in the view's markup. http://stackoverflow.com/questions/1160420/how-do-i-group-data-in-an-asp-net-mvc-view/1160455 – David Fox Jun 14 '10 at 12:45
  • I still don't understand what does view inherit :) – ilija veselica Jun 14 '10 at 12:52
  • when you render the view from your controller, you can pass it whatever you want with the `View()` method. there are several overrides for this method, but you can pass it an object if you want. if you have additional data to be passed, and you insist on doing this grouping in the controller, I think you will have to either 1)adjust your model or 2)wrap your data and IEnumberanle in an object and pass that as a whole. – David Fox Jun 14 '10 at 13:23
  • 1
    Create a view model, and populate it on select like... select new CategoryGroup { Category = y.Key, Items = y } Then you can have a strongly typed view based on `CategoryGroup` – Peter Willis Jun 14 '10 at 20:40