C# 循环浏览 Razor 中的模型内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13078647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through models content in Razor
提问by Rodders
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:
我想在我的剃刀视图中循环浏览模型中的每个项目,但我想将所有项目组合在一起。然后我想遍历每个组。想象一下我有一张桌子:
ID GroupNo GroupName
1 1 Group1
2 1 Group2
3 1 Group3
4 2 Group1
5 2 Group2
6 3 Group56
I want to do something like:
我想做类似的事情:
@foreach (var group in Model.GroupNo) {
<section>
<header>Group No is @group.GroupNo</header>
@foreach (var item in group) {
<p>GroupName: @item.GroupName</p>
}
</section>
}
So my output is:
所以我的输出是:
Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56
Is this possible?
这可能吗?
Thanks
谢谢
采纳答案by McGarnagle
Yes, this is easy to do using the Linq GroupBy. I'd suggest changing your view to use @model IEnumerable<IGrouping<string, MyModel>>, which you'd populate like this:
是的,使用 Linq 很容易做到这一点GroupBy。我建议将您的视图更改为 use @model IEnumerable<IGrouping<string, MyModel>>,您可以像这样填充它:
var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);
Then, simply iterate through the group as you wrote, except using group.Keyinstead of group.GroupNoto retrieve IGrouping's key:
然后,在您编写时简单地遍历组,除了使用group.Key而不是group.GroupNo检索 IGrouping 的键:
@foreach (var group in Model) {
<section>
<header>Group No is @group.Key</header>
@foreach (var item in group) {
<p>GroupName: @item.GroupName</p>
}
</section>
}
回答by codingbiz
LINQ can help you do that
LINQ 可以帮助你做到这一点
@model IEnumerable<Project1.Models.Group>
@foreach (var item in Model.Select(i=>i.groupno).Distinct().ToList()) {
<tr>
<td>
<header>Group No is @item</header>
@foreach (var grpName in Model.Where(i => i.groupno == item).ToList())
{
<p>GroupName: @grpName.groupName</p>
}
</td>
</tr>
}
回答by Prashant Vishwakarma
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@{
String[] name = {"Prashant", "Rishabh", "Zaheer", "Pratima", "Rahul"};
int i = 1;
while (i <= 5)
{
foreach(var x in name)
{
<p>@i. @x</p>
i++;
};
break;
}
}
</div>
</body>
</html>
O/p-
1. Prashant
2. Rishabh
3. Zaheer
4. Pratima
5. Rahul

