13

我想在我的剃刀视图中循环浏览模型中的每个项目,但我想将所有项目组合在一起。然后我想遍历每个组。想象一下我有一张桌子:

ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56

我想做类似的事情:

@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>
} 

所以我的输出是:

Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56

这可能吗?

谢谢

4

3 回答 3

33

是的,使用 Linq 很容易做到这一点GroupBy。我建议将您的视图更改为 use @model IEnumerable<IGrouping<string, MyModel>>,您将像这样填充它:

var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);

然后,只需按照您编写的方式遍历组,除了使用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>
} 
于 2012-10-25T23:11:09.583 回答
10

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>
}
于 2012-10-25T23:39:28.470 回答
-4
@{
    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
于 2017-12-08T10:29:23.507 回答