I want to loop through each item in my model in my razor view but I want to group all items together. I then want to loop through each group. Imagine I have a table:
<
Yes, this is easy to do using the Linq GroupBy
. I'd suggest changing your view to use @model IEnumerable
, which you'd populate like this:
var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);
Then, simply iterate through the group as you wrote, except using group.Key
instead of group.GroupNo
to retrieve IGrouping's key:
@foreach (var group in Model) {
Group No is @group.Key
@foreach (var item in group) {
GroupName: @item.GroupName
}
}