C# 如何在 ASP.NET MVC 视图中对数据进行分组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1160420/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:39:40  来源:igfitidea点击:

How do I group data in an ASP.NET MVC View?

c#asp.net-mvclinqlinq-to-sqlreporting

提问by Robert Harvey

In reporting tools like Crystal Reports, there are ways to take denormalized data and group it by a particular column in the data, creating row headings for each unique item in the specified column.

在 Crystal Reports 等报告工具中,有多种方法可以获取非规范化数据并按数据中的特定列对其进行分组,从而为指定列中的每个唯一项目创建行标题。

If I have this:

如果我有这个:

Category1    Data1
Category1    Data2
Category1    Data3
Category2    Data4
Category2    Data5
Category2    Data6

The reporting software will group it like this:

报告软件将其分组如下:

Category1
      Data1
      Data2
      Date3
Category2
      Data4
      Data5
      Data6

Is there a way to do this in an ASP.NET MVC view, perhaps using a simple linq phrase or linq extension method with a foreach or a nested foreach?

有没有办法在 ASP.NET MVC 视图中执行此操作,也许使用带有 foreach 或嵌套 foreach 的简单 linq 短语或 linq 扩展方法?

采纳答案by Jason

If your view is strongly typed, you can use the LINQ GroupBy extension method with nested foreach:

如果您的视图是强类型的,您可以使用带有嵌套 foreach 的 LINQ GroupBy 扩展方法:

<ul>
<% foreach (var group in Model.GroupBy(item => item.Category)) { %>

   <li><%= Html.Encode(group.Key) %>
     <ul>

     <% foreach (var item in group) { %>
       <li><%= Html.Encode(item.Data) %></li>  
     <% } %>

     </ul>
   </li>

<% } %>
</ul>

This will provide output much like your formatted lists in the original question. It assumes your model looks something like:

这将提供与原始问题中的格式化列表非常相似的输出。它假设您的模型如下所示:

public class ViewModel
{
    public string Category { get; set; }
    public string Data { get; set; }
}

回答by Rahul Bhalekar

<table class="table table-striped table-bordered">
    @foreach (var plan in Model.GroupBy(p => p.PlanName))
    {
        <thead>
            <tr>
                <th></th>
                <th>
                    @plan.Key
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var plan1 in plan)
            {
                <tr>
                    <td>@plan1.PlanDetails</td>
                    <td>@plan1.PlanOption</td>
                </tr>
            }
        </tbody>
        <tfoot>

        </tfoot>
    }

</table>